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 {}
38 pub(crate) fn prepare_rename(
40 position: FilePosition,
41 ) -> Result<RangeInfo<()>, RenameError> {
42 let sema = Semantics::new(db);
43 let source_file = sema.parse(position.file_id);
44 let syntax = source_file.syntax();
45 if let Some(module) = find_module_at_offset(&sema, position, syntax) {
46 rename_mod(&sema, position, module, "dummy")
47 } else if let Some(self_token) =
48 syntax.token_at_offset(position.offset).find(|t| t.kind() == SyntaxKind::SELF_KW)
50 rename_self_to_param(&sema, position, self_token, "dummy")
52 let range = match find_all_refs(&sema, position, None) {
53 Some(RangeInfo { range, .. }) => range,
54 None => return Err(RenameError("No references found at position".to_string())),
56 Ok(RangeInfo::new(range, SourceChange::from(vec![])))
58 .map(|info| RangeInfo::new(info.range, ()))
63 position: FilePosition,
65 ) -> Result<RangeInfo<SourceChange>, RenameError> {
66 let sema = Semantics::new(db);
67 rename_with_semantics(&sema, position, new_name)
70 pub(crate) fn rename_with_semantics(
71 sema: &Semantics<RootDatabase>,
72 position: FilePosition,
74 ) -> Result<RangeInfo<SourceChange>, RenameError> {
75 let is_lifetime_name = match lex_single_syntax_kind(new_name) {
76 Some(res) => match res {
77 (SyntaxKind::IDENT, _) => false,
78 (SyntaxKind::UNDERSCORE, _) => false,
79 (SyntaxKind::SELF_KW, _) => return rename_to_self(&sema, position),
80 (SyntaxKind::LIFETIME_IDENT, _) if new_name != "'static" && new_name != "'_" => true,
81 (SyntaxKind::LIFETIME_IDENT, _) => {
82 return Err(RenameError(format!(
83 "Invalid name `{0}`: Cannot rename lifetime to {0}",
87 (_, Some(syntax_error)) => {
88 return Err(RenameError(format!("Invalid name `{}`: {}", new_name, syntax_error)))
91 return Err(RenameError(format!("Invalid name `{}`: not an identifier", new_name)))
94 None => return Err(RenameError(format!("Invalid name `{}`: not an identifier", new_name))),
97 let source_file = sema.parse(position.file_id);
98 let syntax = source_file.syntax();
99 // this is here to prevent lifetime renames from happening on modules and self
100 if is_lifetime_name {
101 rename_reference(&sema, position, new_name, is_lifetime_name)
102 } else if let Some(module) = find_module_at_offset(&sema, position, syntax) {
103 rename_mod(&sema, position, module, new_name)
104 } else if let Some(self_token) =
105 syntax.token_at_offset(position.offset).find(|t| t.kind() == SyntaxKind::SELF_KW)
107 rename_self_to_param(&sema, position, self_token, new_name)
109 rename_reference(&sema, position, new_name, is_lifetime_name)
113 fn find_module_at_offset(
114 sema: &Semantics<RootDatabase>,
115 position: FilePosition,
117 ) -> Option<Module> {
118 let ident = syntax.token_at_offset(position.offset).find(|t| t.kind() == SyntaxKind::IDENT)?;
120 let module = match_ast! {
121 match (ident.parent()) {
122 ast::NameRef(name_ref) => {
123 match NameRefClass::classify(sema, &name_ref)? {
124 NameRefClass::Definition(Definition::ModuleDef(ModuleDef::Module(module))) => module,
129 match NameClass::classify(&sema, &name)? {
130 NameClass::Definition(Definition::ModuleDef(ModuleDef::Module(module))) => module,
141 fn source_edit_from_reference(
142 sema: &Semantics<RootDatabase>,
143 reference: Reference,
145 ) -> SourceFileEdit {
146 let mut replacement_text = String::new();
147 let range = match reference.kind {
148 ReferenceKind::FieldShorthandForField => {
149 mark::hit!(test_rename_struct_field_for_shorthand);
150 replacement_text.push_str(new_name);
151 replacement_text.push_str(": ");
152 TextRange::new(reference.file_range.range.start(), reference.file_range.range.start())
154 ReferenceKind::FieldShorthandForLocal => {
155 mark::hit!(test_rename_local_for_field_shorthand);
156 replacement_text.push_str(": ");
157 replacement_text.push_str(new_name);
158 TextRange::new(reference.file_range.range.end(), reference.file_range.range.end())
160 ReferenceKind::RecordFieldExprOrPat => {
161 mark::hit!(test_rename_field_expr_pat);
162 replacement_text.push_str(new_name);
163 edit_text_range_for_record_field_expr_or_pat(sema, reference.file_range, new_name)
166 replacement_text.push_str(new_name);
167 reference.file_range.range
171 file_id: reference.file_range.file_id,
172 edit: TextEdit::replace(range, replacement_text),
176 fn edit_text_range_for_record_field_expr_or_pat(
177 sema: &Semantics<RootDatabase>,
178 file_range: FileRange,
181 let source_file = sema.parse(file_range.file_id);
182 let file_syntax = source_file.syntax();
183 let original_range = file_range.range;
185 syntax::algo::find_node_at_range::<ast::RecordExprField>(file_syntax, original_range)
186 .and_then(|field_expr| match field_expr.expr().and_then(|e| e.name_ref()) {
187 Some(name) if &name.to_string() == new_name => Some(field_expr.syntax().text_range()),
191 syntax::algo::find_node_at_range::<ast::RecordPatField>(file_syntax, original_range)
192 .and_then(|field_pat| match field_pat.pat() {
193 Some(ast::Pat::IdentPat(pat))
194 if pat.name().map(|n| n.to_string()).as_deref() == Some(new_name) =>
196 Some(field_pat.syntax().text_range())
201 .unwrap_or(original_range)
205 sema: &Semantics<RootDatabase>,
206 position: FilePosition,
209 ) -> Result<RangeInfo<SourceChange>, RenameError> {
210 let mut source_file_edits = Vec::new();
211 let mut file_system_edits = Vec::new();
213 let src = module.definition_source(sema.db);
214 let file_id = src.file_id.original_file(sema.db);
216 ModuleSource::SourceFile(..) => {
217 // mod is defined in path/to/dir/mod.rs
218 let path = if module.is_mod_rs(sema.db) {
219 format!("../{}/mod.rs", new_name)
221 format!("{}.rs", new_name)
223 let dst = AnchoredPathBuf { anchor: file_id, path };
224 let move_file = FileSystemEdit::MoveFile { src: file_id, dst };
225 file_system_edits.push(move_file);
227 ModuleSource::Module(..) => {}
230 if let Some(src) = module.declaration_source(sema.db) {
231 let file_id = src.file_id.original_file(sema.db);
232 let name = src.value.name().unwrap();
233 let edit = SourceFileEdit {
235 edit: TextEdit::replace(name.syntax().text_range(), new_name.into()),
237 source_file_edits.push(edit);
240 let RangeInfo { range, info: refs } = find_all_refs(sema, position, None)
241 .ok_or_else(|| RenameError("No references found at position".to_string()))?;
245 .map(|reference| source_edit_from_reference(sema, reference, new_name));
246 source_file_edits.extend(ref_edits);
248 Ok(RangeInfo::new(range, SourceChange::from_edits(source_file_edits, file_system_edits)))
252 sema: &Semantics<RootDatabase>,
253 position: FilePosition,
254 ) -> Result<RangeInfo<SourceChange>, RenameError> {
255 let source_file = sema.parse(position.file_id);
256 let syn = source_file.syntax();
258 let (fn_def, fn_ast) = find_node_at_offset::<ast::Fn>(syn, position.offset)
259 .and_then(|fn_ast| sema.to_def(&fn_ast).zip(Some(fn_ast)))
260 .ok_or_else(|| RenameError("No surrounding method declaration found".to_string()))?;
261 let param_range = fn_ast
263 .and_then(|p| p.params().next())
264 .ok_or_else(|| RenameError("Method has no parameters".to_string()))?
267 if !param_range.contains(position.offset) {
268 return Err(RenameError("Only the first parameter can be self".to_string()));
271 let impl_block = find_node_at_offset::<ast::Impl>(syn, position.offset)
272 .and_then(|def| sema.to_def(&def))
273 .ok_or_else(|| RenameError("No impl block found for function".to_string()))?;
274 if fn_def.self_param(sema.db).is_some() {
275 return Err(RenameError("Method already has a self parameter".to_string()));
278 let params = fn_def.assoc_fn_params(sema.db);
280 params.first().ok_or_else(|| RenameError("Method has no parameters".into()))?;
281 let first_param_ty = first_param.ty();
282 let impl_ty = impl_block.target_ty(sema.db);
283 let (ty, self_param) = if impl_ty.remove_ref().is_some() {
284 // if the impl is a ref to the type we can just match the `&T` with self directly
285 (first_param_ty.clone(), "self")
287 first_param_ty.remove_ref().map_or((first_param_ty.clone(), "self"), |ty| {
288 (ty, if first_param_ty.is_mutable_reference() { "&mut self" } else { "&self" })
293 return Err(RenameError("Parameter type differs from impl block type".to_string()));
296 let RangeInfo { range, info: refs } = find_all_refs(sema, position, None)
297 .ok_or_else(|| RenameError("No reference found at position".to_string()))?;
299 let (param_ref, usages): (Vec<Reference>, Vec<Reference>) = refs
301 .partition(|reference| param_range.intersect(reference.file_range.range).is_some());
303 if param_ref.is_empty() {
304 return Err(RenameError("Parameter to rename not found".to_string()));
307 let mut edits = usages
309 .map(|reference| source_edit_from_reference(sema, reference, "self"))
310 .collect::<Vec<_>>();
312 edits.push(SourceFileEdit {
313 file_id: position.file_id,
314 edit: TextEdit::replace(param_range, String::from(self_param)),
317 Ok(RangeInfo::new(range, SourceChange::from(edits)))
320 fn text_edit_from_self_param(
322 self_param: &ast::SelfParam,
324 ) -> Option<TextEdit> {
325 fn target_type_name(impl_def: &ast::Impl) -> Option<String> {
326 if let Some(ast::Type::PathType(p)) = impl_def.self_ty() {
327 return Some(p.path()?.segment()?.name_ref()?.text().to_string());
332 let impl_def = find_node_at_offset::<ast::Impl>(syn, self_param.syntax().text_range().start())?;
333 let type_name = target_type_name(&impl_def)?;
335 let mut replacement_text = String::from(new_name);
336 replacement_text.push_str(": ");
337 match (self_param.amp_token(), self_param.mut_token()) {
339 (Some(_), None) => replacement_text.push('&'),
340 (_, Some(_)) => replacement_text.push_str("&mut "),
342 replacement_text.push_str(type_name.as_str());
344 Some(TextEdit::replace(self_param.syntax().text_range(), replacement_text))
347 fn rename_self_to_param(
348 sema: &Semantics<RootDatabase>,
349 position: FilePosition,
350 self_token: SyntaxToken,
352 ) -> Result<RangeInfo<SourceChange>, RenameError> {
353 let source_file = sema.parse(position.file_id);
354 let syn = source_file.syntax();
356 let text = sema.db.file_text(position.file_id);
357 let fn_def = find_node_at_offset::<ast::Fn>(syn, position.offset)
358 .ok_or_else(|| RenameError("No surrounding method declaration found".to_string()))?;
359 let search_range = fn_def.syntax().text_range();
361 let mut edits: Vec<SourceFileEdit> = vec![];
363 for (idx, _) in text.match_indices("self") {
364 let offset: TextSize = idx.try_into().unwrap();
365 if !search_range.contains_inclusive(offset) {
368 if let Some(ref usage) =
369 syn.token_at_offset(offset).find(|t| t.kind() == SyntaxKind::SELF_KW)
371 let edit = if let Some(ref self_param) = ast::SelfParam::cast(usage.parent()) {
372 text_edit_from_self_param(syn, self_param, new_name)
373 .ok_or_else(|| RenameError("No target type found".to_string()))?
375 TextEdit::replace(usage.text_range(), String::from(new_name))
377 edits.push(SourceFileEdit { file_id: position.file_id, edit });
381 let range = ast::SelfParam::cast(self_token.parent())
382 .map_or(self_token.text_range(), |p| p.syntax().text_range());
384 Ok(RangeInfo::new(range, SourceChange::from(edits)))
388 sema: &Semantics<RootDatabase>,
389 position: FilePosition,
391 is_lifetime_name: bool,
392 ) -> Result<RangeInfo<SourceChange>, RenameError> {
393 let RangeInfo { range, info: refs } = match find_all_refs(sema, position, None) {
394 Some(range_info) => range_info,
395 None => return Err(RenameError("No references found at position".to_string())),
398 match (refs.declaration.kind == ReferenceKind::Lifetime, is_lifetime_name) {
400 return Err(RenameError(format!(
401 "Invalid name `{}`: not a lifetime identifier",
406 return Err(RenameError(format!("Invalid name `{}`: not an identifier", new_name)))
413 .map(|reference| source_edit_from_reference(sema, reference, new_name))
414 .collect::<Vec<_>>();
417 return Err(RenameError("No references found at position".to_string()));
420 Ok(RangeInfo::new(range, SourceChange::from(edit)))
425 use expect_test::{expect, Expect};
426 use stdx::trim_indent;
427 use test_utils::{assert_eq_text, mark};
428 use text_edit::TextEdit;
430 use crate::{fixture, FileId};
432 fn check(new_name: &str, ra_fixture_before: &str, ra_fixture_after: &str) {
433 let ra_fixture_after = &trim_indent(ra_fixture_after);
434 let (analysis, position) = fixture::position(ra_fixture_before);
435 let rename_result = analysis
436 .rename(position, new_name)
437 .unwrap_or_else(|err| panic!("Rename to '{}' was cancelled: {}", new_name, err));
438 match rename_result {
439 Ok(source_change) => {
440 let mut text_edit_builder = TextEdit::builder();
441 let mut file_id: Option<FileId> = None;
442 for edit in source_change.info.source_file_edits {
443 file_id = Some(edit.file_id);
444 for indel in edit.edit.into_iter() {
445 text_edit_builder.replace(indel.delete, indel.insert);
448 let mut result = analysis.file_text(file_id.unwrap()).unwrap().to_string();
449 text_edit_builder.finish().apply(&mut result);
450 assert_eq_text!(ra_fixture_after, &*result);
453 if ra_fixture_after.starts_with("error:") {
454 let error_message = ra_fixture_after
457 .skip("error:".len())
458 .collect::<String>();
459 assert_eq!(error_message.trim(), err.to_string());
462 panic!("Rename to '{}' failed unexpectedly: {}", new_name, err)
468 fn check_expect(new_name: &str, ra_fixture: &str, expect: Expect) {
469 let (analysis, position) = fixture::position(ra_fixture);
470 let source_change = analysis
471 .rename(position, new_name)
473 .expect("Expect returned RangeInfo to be Some, but was None");
474 expect.assert_debug_eq(&source_change)
478 fn test_rename_to_underscore() {
479 check("_", r#"fn main() { let i<|> = 1; }"#, r#"fn main() { let _ = 1; }"#);
483 fn test_rename_to_raw_identifier() {
484 check("r#fn", r#"fn main() { let i<|> = 1; }"#, r#"fn main() { let r#fn = 1; }"#);
488 fn test_rename_to_invalid_identifier1() {
491 r#"fn main() { let i<|> = 1; }"#,
492 "error: Invalid name `invalid!`: not an identifier",
497 fn test_rename_to_invalid_identifier2() {
500 r#"fn main() { let i<|> = 1; }"#,
501 "error: Invalid name `multiple tokens`: not an identifier",
506 fn test_rename_to_invalid_identifier3() {
509 r#"fn main() { let i<|> = 1; }"#,
510 "error: Invalid name `let`: not an identifier",
515 fn test_rename_to_invalid_identifier_lifetime() {
518 r#"fn main() { let i<|> = 1; }"#,
519 "error: Invalid name `'foo`: not an identifier",
524 fn test_rename_to_invalid_identifier_lifetime2() {
527 r#"fn main<'a>(_: &'a<|> ()) {}"#,
528 "error: Invalid name `foo`: not a lifetime identifier",
533 fn test_rename_for_local() {
562 fn test_rename_unresolved_reference() {
565 r#"fn main() { let _ = unresolved_ref<|>; }"#,
566 "error: No references found at position",
571 fn test_rename_for_macro_args() {
575 macro_rules! foo {($i:ident) => {$i} }
582 macro_rules! foo {($i:ident) => {$i} }
592 fn test_rename_for_macro_args_rev() {
596 macro_rules! foo {($i:ident) => {$i} }
603 macro_rules! foo {($i:ident) => {$i} }
613 fn test_rename_for_macro_define_fn() {
617 macro_rules! define_fn {($id:ident) => { fn $id{} }}
624 macro_rules! define_fn {($id:ident) => { fn $id{} }}
634 fn test_rename_for_macro_define_fn_rev() {
638 macro_rules! define_fn {($id:ident) => { fn $id{} }}
645 macro_rules! define_fn {($id:ident) => { fn $id{} }}
655 fn test_rename_for_param_inside() {
656 check("j", r#"fn foo(i : u32) -> u32 { i<|> }"#, r#"fn foo(j : u32) -> u32 { j }"#);
660 fn test_rename_refs_for_fn_param() {
661 check("j", r#"fn foo(i<|> : u32) -> u32 { i }"#, r#"fn foo(j : u32) -> u32 { j }"#);
665 fn test_rename_for_mut_param() {
666 check("j", r#"fn foo(mut i<|> : u32) -> u32 { i }"#, r#"fn foo(mut j : u32) -> u32 { j }"#);
670 fn test_rename_struct_field() {
674 struct Foo { i<|>: i32 }
677 fn new(i: i32) -> Self {
683 struct Foo { j: i32 }
686 fn new(i: i32) -> Self {
695 fn test_rename_struct_field_for_shorthand() {
696 mark::check!(test_rename_struct_field_for_shorthand);
700 struct Foo { i<|>: i32 }
703 fn new(i: i32) -> Self {
709 struct Foo { j: i32 }
712 fn new(i: i32) -> Self {
721 fn test_rename_local_for_field_shorthand() {
722 mark::check!(test_rename_local_for_field_shorthand);
726 struct Foo { i: i32 }
729 fn new(i<|>: i32) -> Self {
735 struct Foo { i: i32 }
738 fn new(j: i32) -> Self {
747 fn test_field_shorthand_correct_struct() {
751 struct Foo { i<|>: i32 }
752 struct Bar { i: i32 }
755 fn new(i: i32) -> Self {
761 struct Foo { j: i32 }
762 struct Bar { i: i32 }
765 fn new(i: i32) -> Self {
774 fn test_shadow_local_for_struct_shorthand() {
778 struct Foo { i: i32 }
780 fn baz(i<|>: i32) -> Self {
789 struct Foo { i: i32 }
791 fn baz(j: i32) -> Self {
792 let x = Foo { i: j };
803 fn test_rename_mod() {
840 dst: AnchoredPathBuf {
856 fn test_rename_mod_in_use_tree() {
866 pub struct FooContent;
869 use crate::foo<|>::FooContent;
908 dst: AnchoredPathBuf {
924 fn test_rename_mod_in_dir() {
957 dst: AnchoredPathBuf {
961 path: "../foo2/mod.rs",
973 fn test_rename_unusually_nested_mod() {
978 mod outer { mod fo<|>o; }
1002 file_system_edits: [
1007 dst: AnchoredPathBuf {
1023 fn test_module_rename_in_path() {
1027 mod <|>foo { pub fn bar() {} }
1029 fn main() { foo::bar(); }
1032 mod baz { pub fn bar() {} }
1034 fn main() { baz::bar(); }
1040 fn test_rename_mod_filename_and_path() {
1059 info: SourceChange {
1060 source_file_edits: [
1088 file_system_edits: [
1093 dst: AnchoredPathBuf {
1109 fn test_enum_variant_from_module_1() {
1114 pub enum Foo { Bar<|> }
1117 fn func(f: foo::Foo) {
1125 pub enum Foo { Baz }
1128 fn func(f: foo::Foo) {
1138 fn test_enum_variant_from_module_2() {
1143 pub struct Foo { pub bar<|>: uint }
1146 fn foo(f: foo::Foo) {
1152 pub struct Foo { pub baz: uint }
1155 fn foo(f: foo::Foo) {
1163 fn test_parameter_to_self() {
1167 struct Foo { i: i32 }
1170 fn f(foo<|>: &mut Foo) -> i32 {
1176 struct Foo { i: i32 }
1179 fn f(&mut self) -> i32 {
1188 struct Foo { i: i32 }
1191 fn f(foo<|>: Foo) -> i32 {
1197 struct Foo { i: i32 }
1209 fn test_parameter_to_self_error_no_impl() {
1213 struct Foo { i: i32 }
1215 fn f(foo<|>: &mut Foo) -> i32 {
1219 "error: No impl block found for function",
1224 struct Foo { i: i32 }
1228 fn f(foo<|>: &mut Foo) -> i32 {
1233 "error: Parameter type differs from impl block type",
1238 fn test_parameter_to_self_error_not_first() {
1242 struct Foo { i: i32 }
1244 fn f(x: (), foo<|>: &mut Foo) -> i32 {
1249 "error: Only the first parameter can be self",
1254 fn test_parameter_to_self_impl_ref() {
1258 struct Foo { i: i32 }
1260 fn f(foo<|>: &Foo) -> i32 {
1266 struct Foo { i: i32 }
1277 fn test_self_to_parameter() {
1281 struct Foo { i: i32 }
1284 fn f(&mut <|>self) -> i32 {
1290 struct Foo { i: i32 }
1293 fn f(foo: &mut Foo) -> i32 {
1302 fn test_owned_self_to_parameter() {
1306 struct Foo { i: i32 }
1309 fn f(<|>self) -> i32 {
1315 struct Foo { i: i32 }
1318 fn f(foo: Foo) -> i32 {
1327 fn test_self_in_path_to_parameter() {
1331 struct Foo { i: i32 }
1334 fn f(&self) -> i32 {
1341 struct Foo { i: i32 }
1344 fn f(foo: &Foo) -> i32 {
1354 fn test_initializer_use_field_init_shorthand() {
1355 mark::check!(test_rename_field_expr_pat);
1359 struct Foo { i<|>: i32 }
1361 fn foo(bar: i32) -> Foo {
1366 struct Foo { bar: i32 }
1368 fn foo(bar: i32) -> Foo {
1376 fn test_struct_field_destructure_into_shorthand() {
1380 struct Foo { i<|>: i32 }
1383 let Foo { i: baz } = foo;
1388 struct Foo { baz: i32 }
1391 let Foo { baz } = foo;
1399 fn test_rename_binding_in_destructure_pat() {
1400 let expected_fixture = r#"
1406 let Foo { i: bar } = foo;
1418 let Foo { i: b } = foo;
1432 let Foo { i } = foo;
1441 fn test_rename_binding_in_destructure_param_pat() {
1449 fn foo(Foo { i }: foo) -> i32 {
1458 fn foo(Foo { i: bar }: foo) -> i32 {
1466 fn test_rename_lifetimes() {
1473 impl<'a> Foo<'a> for &'a () {
1474 fn foo() -> &'a<|> () {
1483 impl<'yeeee> Foo<'yeeee> for &'yeeee () {
1484 fn foo() -> &'yeeee () {
1493 fn test_rename_bind_pat() {
1498 enum CustomOption<T> {
1503 let test_variable = CustomOption::Some(22);
1505 match test_variable {
1506 CustomOption::Some(foo<|>) if foo == 11 => {}
1512 enum CustomOption<T> {
1517 let test_variable = CustomOption::Some(22);
1519 match test_variable {
1520 CustomOption::Some(new_name) if new_name == 11 => {}