1 //! FIXME: write short doc here
8 use hir::{Module, ModuleDef, ModuleSource, Semantics};
9 use ide_db::base_db::{AnchoredPathBuf, FileRange, SourceDatabaseExt};
11 defs::{Definition, NameClass, NameRefClass},
15 algo::find_node_at_offset,
16 ast::{self, NameOwner},
17 lex_single_syntax_kind, match_ast, AstNode, SyntaxKind, SyntaxNode, SyntaxToken,
20 use text_edit::TextEdit;
23 references::find_all_refs, FilePosition, FileSystemEdit, RangeInfo, Reference, ReferenceKind,
24 SourceChange, SourceFileEdit, TextRange, TextSize,
28 pub struct RenameError(pub(crate) String);
30 impl fmt::Display for RenameError {
31 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32 Display::fmt(&self.0, f)
36 impl Error for RenameError {}
40 position: FilePosition,
42 ) -> Result<RangeInfo<SourceChange>, RenameError> {
43 let sema = Semantics::new(db);
44 rename_with_semantics(&sema, position, new_name)
47 pub(crate) fn rename_with_semantics(
48 sema: &Semantics<RootDatabase>,
49 position: FilePosition,
51 ) -> Result<RangeInfo<SourceChange>, RenameError> {
52 match lex_single_syntax_kind(new_name) {
53 Some(res) => match res {
54 (SyntaxKind::IDENT, _) => (),
55 (SyntaxKind::UNDERSCORE, _) => (),
56 (SyntaxKind::SELF_KW, _) => return rename_to_self(&sema, position),
57 (_, Some(syntax_error)) => {
58 return Err(RenameError(format!("Invalid name `{}`: {}", new_name, syntax_error)))
61 return Err(RenameError(format!("Invalid name `{}`: not an identifier", new_name)))
64 None => return Err(RenameError(format!("Invalid name `{}`: not an identifier", new_name))),
67 let source_file = sema.parse(position.file_id);
68 let syntax = source_file.syntax();
69 if let Some(module) = find_module_at_offset(&sema, position, syntax) {
70 rename_mod(&sema, position, module, new_name)
71 } else if let Some(self_token) =
72 syntax.token_at_offset(position.offset).find(|t| t.kind() == SyntaxKind::SELF_KW)
74 rename_self_to_param(&sema, position, self_token, new_name)
76 rename_reference(&sema, position, new_name)
80 fn find_module_at_offset(
81 sema: &Semantics<RootDatabase>,
82 position: FilePosition,
85 let ident = syntax.token_at_offset(position.offset).find(|t| t.kind() == SyntaxKind::IDENT)?;
87 let module = match_ast! {
88 match (ident.parent()) {
89 ast::NameRef(name_ref) => {
90 match NameRefClass::classify(sema, &name_ref)? {
91 NameRefClass::Definition(Definition::ModuleDef(ModuleDef::Module(module))) => module,
96 match NameClass::classify(&sema, &name)? {
97 NameClass::Definition(Definition::ModuleDef(ModuleDef::Module(module))) => module,
108 fn source_edit_from_reference(
109 sema: &Semantics<RootDatabase>,
110 reference: Reference,
112 ) -> SourceFileEdit {
113 let mut replacement_text = String::new();
114 let range = match reference.kind {
115 ReferenceKind::FieldShorthandForField => {
116 mark::hit!(test_rename_struct_field_for_shorthand);
117 replacement_text.push_str(new_name);
118 replacement_text.push_str(": ");
119 TextRange::new(reference.file_range.range.start(), reference.file_range.range.start())
121 ReferenceKind::FieldShorthandForLocal => {
122 mark::hit!(test_rename_local_for_field_shorthand);
123 replacement_text.push_str(": ");
124 replacement_text.push_str(new_name);
125 TextRange::new(reference.file_range.range.end(), reference.file_range.range.end())
127 ReferenceKind::RecordFieldExprOrPat => {
128 mark::hit!(test_rename_field_expr_pat);
129 replacement_text.push_str(new_name);
130 edit_text_range_for_record_field_expr_or_pat(sema, reference.file_range, new_name)
133 replacement_text.push_str(new_name);
134 reference.file_range.range
138 file_id: reference.file_range.file_id,
139 edit: TextEdit::replace(range, replacement_text),
143 fn edit_text_range_for_record_field_expr_or_pat(
144 sema: &Semantics<RootDatabase>,
145 file_range: FileRange,
148 let source_file = sema.parse(file_range.file_id);
149 let file_syntax = source_file.syntax();
150 let original_range = file_range.range;
152 syntax::algo::find_node_at_range::<ast::RecordExprField>(file_syntax, original_range)
153 .and_then(|field_expr| match field_expr.expr().and_then(|e| e.name_ref()) {
154 Some(name) if &name.to_string() == new_name => Some(field_expr.syntax().text_range()),
158 syntax::algo::find_node_at_range::<ast::RecordPatField>(file_syntax, original_range)
159 .and_then(|field_pat| match field_pat.pat() {
160 Some(ast::Pat::IdentPat(pat))
161 if pat.name().map(|n| n.to_string()).as_deref() == Some(new_name) =>
163 Some(field_pat.syntax().text_range())
168 .unwrap_or(original_range)
172 sema: &Semantics<RootDatabase>,
173 position: FilePosition,
176 ) -> Result<RangeInfo<SourceChange>, RenameError> {
177 let mut source_file_edits = Vec::new();
178 let mut file_system_edits = Vec::new();
180 let src = module.definition_source(sema.db);
181 let file_id = src.file_id.original_file(sema.db);
183 ModuleSource::SourceFile(..) => {
184 // mod is defined in path/to/dir/mod.rs
185 let path = if module.is_mod_rs(sema.db) {
186 format!("../{}/mod.rs", new_name)
188 format!("{}.rs", new_name)
190 let dst = AnchoredPathBuf { anchor: file_id, path };
191 let move_file = FileSystemEdit::MoveFile { src: file_id, dst };
192 file_system_edits.push(move_file);
194 ModuleSource::Module(..) => {}
197 if let Some(src) = module.declaration_source(sema.db) {
198 let file_id = src.file_id.original_file(sema.db);
199 let name = src.value.name().unwrap();
200 let edit = SourceFileEdit {
202 edit: TextEdit::replace(name.syntax().text_range(), new_name.into()),
204 source_file_edits.push(edit);
207 let RangeInfo { range, info: refs } = find_all_refs(sema, position, None)
208 .ok_or_else(|| RenameError("No references found at position".to_string()))?;
212 .map(|reference| source_edit_from_reference(sema, reference, new_name));
213 source_file_edits.extend(ref_edits);
215 Ok(RangeInfo::new(range, SourceChange::from_edits(source_file_edits, file_system_edits)))
219 sema: &Semantics<RootDatabase>,
220 position: FilePosition,
221 ) -> Result<RangeInfo<SourceChange>, RenameError> {
222 let source_file = sema.parse(position.file_id);
223 let syn = source_file.syntax();
225 let (fn_def, fn_ast) = find_node_at_offset::<ast::Fn>(syn, position.offset)
226 .and_then(|fn_ast| sema.to_def(&fn_ast).zip(Some(fn_ast)))
227 .ok_or_else(|| RenameError("No surrounding method declaration found".to_string()))?;
228 let param_range = fn_ast
230 .and_then(|p| p.params().next())
231 .ok_or_else(|| RenameError("Method has no parameters".to_string()))?
234 if !param_range.contains(position.offset) {
235 return Err(RenameError("Only the first parameter can be self".to_string()));
238 let impl_block = find_node_at_offset::<ast::Impl>(syn, position.offset)
239 .and_then(|def| sema.to_def(&def))
240 .ok_or_else(|| RenameError("No impl block found for function".to_string()))?;
241 if fn_def.self_param(sema.db).is_some() {
242 return Err(RenameError("Method already has a self parameter".to_string()));
245 let params = fn_def.assoc_fn_params(sema.db);
247 params.first().ok_or_else(|| RenameError("Method has no parameters".into()))?;
248 let first_param_ty = first_param.ty();
249 let impl_ty = impl_block.target_ty(sema.db);
250 let (ty, self_param) = if impl_ty.remove_ref().is_some() {
251 // if the impl is a ref to the type we can just match the `&T` with self directly
252 (first_param_ty.clone(), "self")
254 first_param_ty.remove_ref().map_or((first_param_ty.clone(), "self"), |ty| {
255 (ty, if first_param_ty.is_mutable_reference() { "&mut self" } else { "&self" })
260 return Err(RenameError("Parameter type differs from impl block type".to_string()));
263 let RangeInfo { range, info: refs } = find_all_refs(sema, position, None)
264 .ok_or_else(|| RenameError("No reference found at position".to_string()))?;
266 let (param_ref, usages): (Vec<Reference>, Vec<Reference>) = refs
268 .partition(|reference| param_range.intersect(reference.file_range.range).is_some());
270 if param_ref.is_empty() {
271 return Err(RenameError("Parameter to rename not found".to_string()));
274 let mut edits = usages
276 .map(|reference| source_edit_from_reference(sema, reference, "self"))
277 .collect::<Vec<_>>();
279 edits.push(SourceFileEdit {
280 file_id: position.file_id,
281 edit: TextEdit::replace(param_range, String::from(self_param)),
284 Ok(RangeInfo::new(range, SourceChange::from(edits)))
287 fn text_edit_from_self_param(
289 self_param: &ast::SelfParam,
291 ) -> Option<TextEdit> {
292 fn target_type_name(impl_def: &ast::Impl) -> Option<String> {
293 if let Some(ast::Type::PathType(p)) = impl_def.self_ty() {
294 return Some(p.path()?.segment()?.name_ref()?.text().to_string());
299 let impl_def = find_node_at_offset::<ast::Impl>(syn, self_param.syntax().text_range().start())?;
300 let type_name = target_type_name(&impl_def)?;
302 let mut replacement_text = String::from(new_name);
303 replacement_text.push_str(": ");
304 match (self_param.amp_token(), self_param.mut_token()) {
306 (Some(_), None) => replacement_text.push('&'),
307 (_, Some(_)) => replacement_text.push_str("&mut "),
309 replacement_text.push_str(type_name.as_str());
311 Some(TextEdit::replace(self_param.syntax().text_range(), replacement_text))
314 fn rename_self_to_param(
315 sema: &Semantics<RootDatabase>,
316 position: FilePosition,
317 self_token: SyntaxToken,
319 ) -> Result<RangeInfo<SourceChange>, RenameError> {
320 let source_file = sema.parse(position.file_id);
321 let syn = source_file.syntax();
323 let text = sema.db.file_text(position.file_id);
324 let fn_def = find_node_at_offset::<ast::Fn>(syn, position.offset)
325 .ok_or_else(|| RenameError("No surrounding method declaration found".to_string()))?;
326 let search_range = fn_def.syntax().text_range();
328 let mut edits: Vec<SourceFileEdit> = vec![];
330 for (idx, _) in text.match_indices("self") {
331 let offset: TextSize = idx.try_into().unwrap();
332 if !search_range.contains_inclusive(offset) {
335 if let Some(ref usage) =
336 syn.token_at_offset(offset).find(|t| t.kind() == SyntaxKind::SELF_KW)
338 let edit = if let Some(ref self_param) = ast::SelfParam::cast(usage.parent()) {
339 text_edit_from_self_param(syn, self_param, new_name)
340 .ok_or_else(|| RenameError("No target type found".to_string()))?
342 TextEdit::replace(usage.text_range(), String::from(new_name))
344 edits.push(SourceFileEdit { file_id: position.file_id, edit });
348 let range = ast::SelfParam::cast(self_token.parent())
349 .map_or(self_token.text_range(), |p| p.syntax().text_range());
351 Ok(RangeInfo::new(range, SourceChange::from(edits)))
355 sema: &Semantics<RootDatabase>,
356 position: FilePosition,
358 ) -> Result<RangeInfo<SourceChange>, RenameError> {
359 let RangeInfo { range, info: refs } = match find_all_refs(sema, position, None) {
360 Some(range_info) => range_info,
361 None => return Err(RenameError("No references found at position".to_string())),
366 .map(|reference| source_edit_from_reference(sema, reference, new_name))
367 .collect::<Vec<_>>();
370 return Err(RenameError("No references found at position".to_string()));
373 Ok(RangeInfo::new(range, SourceChange::from(edit)))
378 use expect_test::{expect, Expect};
379 use stdx::trim_indent;
380 use test_utils::{assert_eq_text, mark};
381 use text_edit::TextEdit;
383 use crate::{fixture, FileId};
385 fn check(new_name: &str, ra_fixture_before: &str, ra_fixture_after: &str) {
386 let ra_fixture_after = &trim_indent(ra_fixture_after);
387 let (analysis, position) = fixture::position(ra_fixture_before);
388 let rename_result = analysis
389 .rename(position, new_name)
390 .unwrap_or_else(|err| panic!("Rename to '{}' was cancelled: {}", new_name, err));
391 match rename_result {
392 Ok(source_change) => {
393 let mut text_edit_builder = TextEdit::builder();
394 let mut file_id: Option<FileId> = None;
395 for edit in source_change.info.source_file_edits {
396 file_id = Some(edit.file_id);
397 for indel in edit.edit.into_iter() {
398 text_edit_builder.replace(indel.delete, indel.insert);
401 let mut result = analysis.file_text(file_id.unwrap()).unwrap().to_string();
402 text_edit_builder.finish().apply(&mut result);
403 assert_eq_text!(ra_fixture_after, &*result);
406 if ra_fixture_after.starts_with("error:") {
407 let error_message = ra_fixture_after
410 .skip("error:".len())
411 .collect::<String>();
412 assert_eq!(error_message.trim(), err.to_string());
415 panic!("Rename to '{}' failed unexpectedly: {}", new_name, err)
421 fn check_expect(new_name: &str, ra_fixture: &str, expect: Expect) {
422 let (analysis, position) = fixture::position(ra_fixture);
423 let source_change = analysis
424 .rename(position, new_name)
426 .expect("Expect returned RangeInfo to be Some, but was None");
427 expect.assert_debug_eq(&source_change)
431 fn test_rename_to_underscore() {
432 check("_", r#"fn main() { let i<|> = 1; }"#, r#"fn main() { let _ = 1; }"#);
436 fn test_rename_to_raw_identifier() {
437 check("r#fn", r#"fn main() { let i<|> = 1; }"#, r#"fn main() { let r#fn = 1; }"#);
441 fn test_rename_to_invalid_identifier1() {
444 r#"fn main() { let i<|> = 1; }"#,
445 "error: Invalid name `invalid!`: not an identifier",
450 fn test_rename_to_invalid_identifier2() {
453 r#"fn main() { let i<|> = 1; }"#,
454 "error: Invalid name `multiple tokens`: not an identifier",
459 fn test_rename_to_invalid_identifier3() {
462 r#"fn main() { let i<|> = 1; }"#,
463 "error: Invalid name `let`: not an identifier",
468 fn test_rename_for_local() {
497 fn test_rename_unresolved_reference() {
500 r#"fn main() { let _ = unresolved_ref<|>; }"#,
501 "error: No references found at position",
506 fn test_rename_for_macro_args() {
510 macro_rules! foo {($i:ident) => {$i} }
517 macro_rules! foo {($i:ident) => {$i} }
527 fn test_rename_for_macro_args_rev() {
531 macro_rules! foo {($i:ident) => {$i} }
538 macro_rules! foo {($i:ident) => {$i} }
548 fn test_rename_for_macro_define_fn() {
552 macro_rules! define_fn {($id:ident) => { fn $id{} }}
559 macro_rules! define_fn {($id:ident) => { fn $id{} }}
569 fn test_rename_for_macro_define_fn_rev() {
573 macro_rules! define_fn {($id:ident) => { fn $id{} }}
580 macro_rules! define_fn {($id:ident) => { fn $id{} }}
590 fn test_rename_for_param_inside() {
591 check("j", r#"fn foo(i : u32) -> u32 { i<|> }"#, r#"fn foo(j : u32) -> u32 { j }"#);
595 fn test_rename_refs_for_fn_param() {
596 check("j", r#"fn foo(i<|> : u32) -> u32 { i }"#, r#"fn foo(j : u32) -> u32 { j }"#);
600 fn test_rename_for_mut_param() {
601 check("j", r#"fn foo(mut i<|> : u32) -> u32 { i }"#, r#"fn foo(mut j : u32) -> u32 { j }"#);
605 fn test_rename_struct_field() {
609 struct Foo { i<|>: i32 }
612 fn new(i: i32) -> Self {
618 struct Foo { j: i32 }
621 fn new(i: i32) -> Self {
630 fn test_rename_struct_field_for_shorthand() {
631 mark::check!(test_rename_struct_field_for_shorthand);
635 struct Foo { i<|>: i32 }
638 fn new(i: i32) -> Self {
644 struct Foo { j: i32 }
647 fn new(i: i32) -> Self {
656 fn test_rename_local_for_field_shorthand() {
657 mark::check!(test_rename_local_for_field_shorthand);
661 struct Foo { i: i32 }
664 fn new(i<|>: i32) -> Self {
670 struct Foo { i: i32 }
673 fn new(j: i32) -> Self {
682 fn test_field_shorthand_correct_struct() {
686 struct Foo { i<|>: i32 }
687 struct Bar { i: i32 }
690 fn new(i: i32) -> Self {
696 struct Foo { j: i32 }
697 struct Bar { i: i32 }
700 fn new(i: i32) -> Self {
709 fn test_shadow_local_for_struct_shorthand() {
713 struct Foo { i: i32 }
715 fn baz(i<|>: i32) -> Self {
724 struct Foo { i: i32 }
726 fn baz(j: i32) -> Self {
727 let x = Foo { i: j };
738 fn test_rename_mod() {
775 dst: AnchoredPathBuf {
791 fn test_rename_mod_in_use_tree() {
801 pub struct FooContent;
804 use crate::foo<|>::FooContent;
843 dst: AnchoredPathBuf {
859 fn test_rename_mod_in_dir() {
892 dst: AnchoredPathBuf {
896 path: "../foo2/mod.rs",
908 fn test_rename_unusually_nested_mod() {
913 mod outer { mod fo<|>o; }
942 dst: AnchoredPathBuf {
958 fn test_module_rename_in_path() {
962 mod <|>foo { pub fn bar() {} }
964 fn main() { foo::bar(); }
967 mod baz { pub fn bar() {} }
969 fn main() { baz::bar(); }
975 fn test_rename_mod_filename_and_path() {
1023 file_system_edits: [
1028 dst: AnchoredPathBuf {
1044 fn test_enum_variant_from_module_1() {
1049 pub enum Foo { Bar<|> }
1052 fn func(f: foo::Foo) {
1060 pub enum Foo { Baz }
1063 fn func(f: foo::Foo) {
1073 fn test_enum_variant_from_module_2() {
1078 pub struct Foo { pub bar<|>: uint }
1081 fn foo(f: foo::Foo) {
1087 pub struct Foo { pub baz: uint }
1090 fn foo(f: foo::Foo) {
1098 fn test_parameter_to_self() {
1102 struct Foo { i: i32 }
1105 fn f(foo<|>: &mut Foo) -> i32 {
1111 struct Foo { i: i32 }
1114 fn f(&mut self) -> i32 {
1123 struct Foo { i: i32 }
1126 fn f(foo<|>: Foo) -> i32 {
1132 struct Foo { i: i32 }
1144 fn test_parameter_to_self_error_no_impl() {
1148 struct Foo { i: i32 }
1150 fn f(foo<|>: &mut Foo) -> i32 {
1154 "error: No impl block found for function",
1159 struct Foo { i: i32 }
1163 fn f(foo<|>: &mut Foo) -> i32 {
1168 "error: Parameter type differs from impl block type",
1173 fn test_parameter_to_self_error_not_first() {
1177 struct Foo { i: i32 }
1179 fn f(x: (), foo<|>: &mut Foo) -> i32 {
1184 "error: Only the first parameter can be self",
1189 fn test_parameter_to_self_impl_ref() {
1193 struct Foo { i: i32 }
1195 fn f(foo<|>: &Foo) -> i32 {
1201 struct Foo { i: i32 }
1212 fn test_self_to_parameter() {
1216 struct Foo { i: i32 }
1219 fn f(&mut <|>self) -> i32 {
1225 struct Foo { i: i32 }
1228 fn f(foo: &mut Foo) -> i32 {
1237 fn test_owned_self_to_parameter() {
1241 struct Foo { i: i32 }
1244 fn f(<|>self) -> i32 {
1250 struct Foo { i: i32 }
1253 fn f(foo: Foo) -> i32 {
1262 fn test_self_in_path_to_parameter() {
1266 struct Foo { i: i32 }
1269 fn f(&self) -> i32 {
1276 struct Foo { i: i32 }
1279 fn f(foo: &Foo) -> i32 {
1289 fn test_initializer_use_field_init_shorthand() {
1290 mark::check!(test_rename_field_expr_pat);
1294 struct Foo { i<|>: i32 }
1296 fn foo(bar: i32) -> Foo {
1301 struct Foo { bar: i32 }
1303 fn foo(bar: i32) -> Foo {
1311 fn test_struct_field_destructure_into_shorthand() {
1315 struct Foo { i<|>: i32 }
1318 let Foo { i: baz } = foo;
1323 struct Foo { baz: i32 }
1326 let Foo { baz } = foo;
1334 fn test_rename_binding_in_destructure_pat() {
1335 let expected_fixture = r#"
1341 let Foo { i: bar } = foo;
1353 let Foo { i: b } = foo;
1367 let Foo { i } = foo;
1376 fn test_rename_binding_in_destructure_param_pat() {
1384 fn foo(Foo { i }: foo) -> i32 {
1393 fn foo(Foo { i: bar }: foo) -> i32 {