1 //! FIXME: write short doc here
8 use hir::{Module, ModuleDef, ModuleSource, Semantics};
9 use ide_db::base_db::{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 dst = if module.is_mod_rs(sema.db) {
186 format!("../{}/mod.rs", new_name)
188 format!("{}.rs", new_name)
190 let move_file = FileSystemEdit::MoveFile { src: file_id, anchor: file_id, dst };
191 file_system_edits.push(move_file);
193 ModuleSource::Module(..) => {}
196 if let Some(src) = module.declaration_source(sema.db) {
197 let file_id = src.file_id.original_file(sema.db);
198 let name = src.value.name().unwrap();
199 let edit = SourceFileEdit {
201 edit: TextEdit::replace(name.syntax().text_range(), new_name.into()),
203 source_file_edits.push(edit);
206 let RangeInfo { range, info: refs } = find_all_refs(sema, position, None)
207 .ok_or_else(|| RenameError("No references found at position".to_string()))?;
211 .map(|reference| source_edit_from_reference(sema, reference, new_name));
212 source_file_edits.extend(ref_edits);
214 Ok(RangeInfo::new(range, SourceChange::from_edits(source_file_edits, file_system_edits)))
218 sema: &Semantics<RootDatabase>,
219 position: FilePosition,
220 ) -> Result<RangeInfo<SourceChange>, RenameError> {
221 let source_file = sema.parse(position.file_id);
222 let syn = source_file.syntax();
224 let fn_def = find_node_at_offset::<ast::Fn>(syn, position.offset)
225 .ok_or_else(|| RenameError("No surrounding method declaration found".to_string()))?;
227 fn_def.param_list().ok_or_else(|| RenameError("Method has no parameters".to_string()))?;
228 if params.self_param().is_some() {
229 return Err(RenameError("Method already has a self parameter".to_string()));
232 params.params().next().ok_or_else(|| RenameError("Method has no parameters".into()))?;
233 let mutable = match first_param.ty() {
234 Some(ast::Type::RefType(rt)) => rt.mut_token().is_some(),
235 _ => return Err(RenameError("Not renaming other types".to_string())),
238 let RangeInfo { range, info: refs } = find_all_refs(sema, position, None)
239 .ok_or_else(|| RenameError("No reference found at position".to_string()))?;
241 let param_range = first_param.syntax().text_range();
242 let (param_ref, usages): (Vec<Reference>, Vec<Reference>) = refs
244 .partition(|reference| param_range.intersect(reference.file_range.range).is_some());
246 if param_ref.is_empty() {
247 return Err(RenameError("Parameter to rename not found".to_string()));
250 let mut edits = usages
252 .map(|reference| source_edit_from_reference(sema, reference, "self"))
253 .collect::<Vec<_>>();
255 edits.push(SourceFileEdit {
256 file_id: position.file_id,
257 edit: TextEdit::replace(
259 String::from(if mutable { "&mut self" } else { "&self" }),
263 Ok(RangeInfo::new(range, SourceChange::from(edits)))
266 fn text_edit_from_self_param(
268 self_param: &ast::SelfParam,
270 ) -> Option<TextEdit> {
271 fn target_type_name(impl_def: &ast::Impl) -> Option<String> {
272 if let Some(ast::Type::PathType(p)) = impl_def.self_ty() {
273 return Some(p.path()?.segment()?.name_ref()?.text().to_string());
278 let impl_def = find_node_at_offset::<ast::Impl>(syn, self_param.syntax().text_range().start())?;
279 let type_name = target_type_name(&impl_def)?;
281 let mut replacement_text = String::from(new_name);
282 replacement_text.push_str(": ");
283 match (self_param.amp_token(), self_param.mut_token()) {
285 (Some(_), None) => replacement_text.push('&'),
286 (_, Some(_)) => replacement_text.push_str("&mut "),
288 replacement_text.push_str(type_name.as_str());
290 Some(TextEdit::replace(self_param.syntax().text_range(), replacement_text))
293 fn rename_self_to_param(
294 sema: &Semantics<RootDatabase>,
295 position: FilePosition,
296 self_token: SyntaxToken,
298 ) -> Result<RangeInfo<SourceChange>, RenameError> {
299 let source_file = sema.parse(position.file_id);
300 let syn = source_file.syntax();
302 let text = sema.db.file_text(position.file_id);
303 let fn_def = find_node_at_offset::<ast::Fn>(syn, position.offset)
304 .ok_or_else(|| RenameError("No surrounding method declaration found".to_string()))?;
305 let search_range = fn_def.syntax().text_range();
307 let mut edits: Vec<SourceFileEdit> = vec![];
309 for (idx, _) in text.match_indices("self") {
310 let offset: TextSize = idx.try_into().unwrap();
311 if !search_range.contains_inclusive(offset) {
314 if let Some(ref usage) =
315 syn.token_at_offset(offset).find(|t| t.kind() == SyntaxKind::SELF_KW)
317 let edit = if let Some(ref self_param) = ast::SelfParam::cast(usage.parent()) {
318 text_edit_from_self_param(syn, self_param, new_name)
319 .ok_or_else(|| RenameError("No target type found".to_string()))?
321 TextEdit::replace(usage.text_range(), String::from(new_name))
323 edits.push(SourceFileEdit { file_id: position.file_id, edit });
327 let range = ast::SelfParam::cast(self_token.parent())
328 .map_or(self_token.text_range(), |p| p.syntax().text_range());
330 Ok(RangeInfo::new(range, SourceChange::from(edits)))
334 sema: &Semantics<RootDatabase>,
335 position: FilePosition,
337 ) -> Result<RangeInfo<SourceChange>, RenameError> {
338 let RangeInfo { range, info: refs } = match find_all_refs(sema, position, None) {
339 Some(range_info) => range_info,
340 None => return Err(RenameError("No references found at position".to_string())),
345 .map(|reference| source_edit_from_reference(sema, reference, new_name))
346 .collect::<Vec<_>>();
349 return Err(RenameError("No references found at position".to_string()));
352 Ok(RangeInfo::new(range, SourceChange::from(edit)))
357 use expect_test::{expect, Expect};
358 use stdx::trim_indent;
359 use test_utils::{assert_eq_text, mark};
360 use text_edit::TextEdit;
362 use crate::{fixture, FileId};
364 fn check(new_name: &str, ra_fixture_before: &str, ra_fixture_after: &str) {
365 let ra_fixture_after = &trim_indent(ra_fixture_after);
366 let (analysis, position) = fixture::position(ra_fixture_before);
367 let rename_result = analysis
368 .rename(position, new_name)
369 .unwrap_or_else(|err| panic!("Rename to '{}' was cancelled: {}", new_name, err));
370 match rename_result {
371 Ok(source_change) => {
372 let mut text_edit_builder = TextEdit::builder();
373 let mut file_id: Option<FileId> = None;
374 for edit in source_change.info.source_file_edits {
375 file_id = Some(edit.file_id);
376 for indel in edit.edit.into_iter() {
377 text_edit_builder.replace(indel.delete, indel.insert);
380 let mut result = analysis.file_text(file_id.unwrap()).unwrap().to_string();
381 text_edit_builder.finish().apply(&mut result);
382 assert_eq_text!(ra_fixture_after, &*result);
385 if ra_fixture_after.starts_with("error:") {
386 let error_message = ra_fixture_after
389 .skip("error:".len())
390 .collect::<String>();
391 assert_eq!(error_message.trim(), err.to_string());
394 panic!("Rename to '{}' failed unexpectedly: {}", new_name, err)
400 fn check_expect(new_name: &str, ra_fixture: &str, expect: Expect) {
401 let (analysis, position) = fixture::position(ra_fixture);
402 let source_change = analysis
403 .rename(position, new_name)
405 .expect("Expect returned RangeInfo to be Some, but was None");
406 expect.assert_debug_eq(&source_change)
410 fn test_rename_to_underscore() {
411 check("_", r#"fn main() { let i<|> = 1; }"#, r#"fn main() { let _ = 1; }"#);
415 fn test_rename_to_raw_identifier() {
416 check("r#fn", r#"fn main() { let i<|> = 1; }"#, r#"fn main() { let r#fn = 1; }"#);
420 fn test_rename_to_invalid_identifier1() {
423 r#"fn main() { let i<|> = 1; }"#,
424 "error: Invalid name `invalid!`: not an identifier",
429 fn test_rename_to_invalid_identifier2() {
432 r#"fn main() { let i<|> = 1; }"#,
433 "error: Invalid name `multiple tokens`: not an identifier",
438 fn test_rename_to_invalid_identifier3() {
441 r#"fn main() { let i<|> = 1; }"#,
442 "error: Invalid name `let`: not an identifier",
447 fn test_rename_for_local() {
476 fn test_rename_unresolved_reference() {
479 r#"fn main() { let _ = unresolved_ref<|>; }"#,
480 "error: No references found at position",
485 fn test_rename_for_macro_args() {
489 macro_rules! foo {($i:ident) => {$i} }
496 macro_rules! foo {($i:ident) => {$i} }
506 fn test_rename_for_macro_args_rev() {
510 macro_rules! foo {($i:ident) => {$i} }
517 macro_rules! foo {($i:ident) => {$i} }
527 fn test_rename_for_macro_define_fn() {
531 macro_rules! define_fn {($id:ident) => { fn $id{} }}
538 macro_rules! define_fn {($id:ident) => { fn $id{} }}
548 fn test_rename_for_macro_define_fn_rev() {
552 macro_rules! define_fn {($id:ident) => { fn $id{} }}
559 macro_rules! define_fn {($id:ident) => { fn $id{} }}
569 fn test_rename_for_param_inside() {
570 check("j", r#"fn foo(i : u32) -> u32 { i<|> }"#, r#"fn foo(j : u32) -> u32 { j }"#);
574 fn test_rename_refs_for_fn_param() {
575 check("j", r#"fn foo(i<|> : u32) -> u32 { i }"#, r#"fn foo(j : u32) -> u32 { j }"#);
579 fn test_rename_for_mut_param() {
580 check("j", r#"fn foo(mut i<|> : u32) -> u32 { i }"#, r#"fn foo(mut j : u32) -> u32 { j }"#);
584 fn test_rename_struct_field() {
588 struct Foo { i<|>: i32 }
591 fn new(i: i32) -> Self {
597 struct Foo { j: i32 }
600 fn new(i: i32) -> Self {
609 fn test_rename_struct_field_for_shorthand() {
610 mark::check!(test_rename_struct_field_for_shorthand);
614 struct Foo { i<|>: i32 }
617 fn new(i: i32) -> Self {
623 struct Foo { j: i32 }
626 fn new(i: i32) -> Self {
635 fn test_rename_local_for_field_shorthand() {
636 mark::check!(test_rename_local_for_field_shorthand);
640 struct Foo { i: i32 }
643 fn new(i<|>: i32) -> Self {
649 struct Foo { i: i32 }
652 fn new(j: i32) -> Self {
661 fn test_field_shorthand_correct_struct() {
665 struct Foo { i<|>: i32 }
666 struct Bar { i: i32 }
669 fn new(i: i32) -> Self {
675 struct Foo { j: i32 }
676 struct Bar { i: i32 }
679 fn new(i: i32) -> Self {
688 fn test_shadow_local_for_struct_shorthand() {
692 struct Foo { i: i32 }
694 fn baz(i<|>: i32) -> Self {
703 struct Foo { i: i32 }
705 fn baz(j: i32) -> Self {
706 let x = Foo { i: j };
717 fn test_rename_mod() {
768 fn test_rename_mod_in_use_tree() {
778 pub struct FooContent;
781 use crate::foo<|>::FooContent;
834 fn test_rename_mod_in_dir() {
870 dst: "../foo2/mod.rs",
881 fn test_rename_unusually_nested_mod() {
886 mod outer { mod fo<|>o; }
929 fn test_module_rename_in_path() {
933 mod <|>foo { pub fn bar() {} }
935 fn main() { foo::bar(); }
938 mod baz { pub fn bar() {} }
940 fn main() { baz::bar(); }
946 fn test_rename_mod_filename_and_path() {
1013 fn test_enum_variant_from_module_1() {
1018 pub enum Foo { Bar<|> }
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<|>: 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() {
1071 struct Foo { i: i32 }
1074 fn f(foo<|>: &mut Foo) -> i32 {
1080 struct Foo { i: i32 }
1083 fn f(&mut self) -> i32 {
1092 fn test_self_to_parameter() {
1096 struct Foo { i: i32 }
1099 fn f(&mut <|>self) -> i32 {
1105 struct Foo { i: i32 }
1108 fn f(foo: &mut Foo) -> i32 {
1117 fn test_owned_self_to_parameter() {
1121 struct Foo { i: i32 }
1124 fn f(<|>self) -> i32 {
1130 struct Foo { i: i32 }
1133 fn f(foo: Foo) -> i32 {
1142 fn test_self_in_path_to_parameter() {
1146 struct Foo { i: i32 }
1149 fn f(&self) -> i32 {
1156 struct Foo { i: i32 }
1159 fn f(foo: &Foo) -> i32 {
1169 fn test_initializer_use_field_init_shorthand() {
1170 mark::check!(test_rename_field_expr_pat);
1174 struct Foo { i<|>: i32 }
1176 fn foo(bar: i32) -> Foo {
1181 struct Foo { bar: i32 }
1183 fn foo(bar: i32) -> Foo {
1191 fn test_struct_field_destructure_into_shorthand() {
1195 struct Foo { i<|>: i32 }
1198 let Foo { i: baz } = foo;
1203 struct Foo { baz: i32 }
1206 let Foo { baz } = foo;
1214 fn test_rename_binding_in_destructure_pat() {
1215 let expected_fixture = r#"
1221 let Foo { i: bar } = foo;
1233 let Foo { i: b } = foo;
1247 let Foo { i } = foo;
1256 fn test_rename_binding_in_destructure_param_pat() {
1264 fn foo(Foo { i }: foo) -> i32 {
1273 fn foo(Foo { i: bar }: foo) -> i32 {