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 replacement_text.push_str(self_param.mut_token().map_or("&", |_| "&mut "));
284 replacement_text.push_str(type_name.as_str());
286 Some(TextEdit::replace(self_param.syntax().text_range(), replacement_text))
289 fn rename_self_to_param(
290 sema: &Semantics<RootDatabase>,
291 position: FilePosition,
292 self_token: SyntaxToken,
294 ) -> Result<RangeInfo<SourceChange>, RenameError> {
295 let source_file = sema.parse(position.file_id);
296 let syn = source_file.syntax();
298 let text = sema.db.file_text(position.file_id);
299 let fn_def = find_node_at_offset::<ast::Fn>(syn, position.offset)
300 .ok_or_else(|| RenameError("No surrounding method declaration found".to_string()))?;
301 let search_range = fn_def.syntax().text_range();
303 let mut edits: Vec<SourceFileEdit> = vec![];
305 for (idx, _) in text.match_indices("self") {
306 let offset: TextSize = idx.try_into().unwrap();
307 if !search_range.contains_inclusive(offset) {
310 if let Some(ref usage) =
311 syn.token_at_offset(offset).find(|t| t.kind() == SyntaxKind::SELF_KW)
313 let edit = if let Some(ref self_param) = ast::SelfParam::cast(usage.parent()) {
314 text_edit_from_self_param(syn, self_param, new_name)
315 .ok_or_else(|| RenameError("No target type found".to_string()))?
317 TextEdit::replace(usage.text_range(), String::from(new_name))
319 edits.push(SourceFileEdit { file_id: position.file_id, edit });
323 let range = ast::SelfParam::cast(self_token.parent())
324 .map_or(self_token.text_range(), |p| p.syntax().text_range());
326 Ok(RangeInfo::new(range, SourceChange::from(edits)))
330 sema: &Semantics<RootDatabase>,
331 position: FilePosition,
333 ) -> Result<RangeInfo<SourceChange>, RenameError> {
334 let RangeInfo { range, info: refs } = match find_all_refs(sema, position, None) {
335 Some(range_info) => range_info,
336 None => return Err(RenameError("No references found at position".to_string())),
341 .map(|reference| source_edit_from_reference(sema, reference, new_name))
342 .collect::<Vec<_>>();
345 return Err(RenameError("No references found at position".to_string()));
348 Ok(RangeInfo::new(range, SourceChange::from(edit)))
353 use expect_test::{expect, Expect};
354 use stdx::trim_indent;
355 use test_utils::{assert_eq_text, mark};
356 use text_edit::TextEdit;
358 use crate::{fixture, FileId};
360 fn check(new_name: &str, ra_fixture_before: &str, ra_fixture_after: &str) {
361 let ra_fixture_after = &trim_indent(ra_fixture_after);
362 let (analysis, position) = fixture::position(ra_fixture_before);
363 let rename_result = analysis
364 .rename(position, new_name)
365 .unwrap_or_else(|err| panic!("Rename to '{}' was cancelled: {}", new_name, err));
366 match rename_result {
367 Ok(source_change) => {
368 let mut text_edit_builder = TextEdit::builder();
369 let mut file_id: Option<FileId> = None;
370 for edit in source_change.info.source_file_edits {
371 file_id = Some(edit.file_id);
372 for indel in edit.edit.into_iter() {
373 text_edit_builder.replace(indel.delete, indel.insert);
376 let mut result = analysis.file_text(file_id.unwrap()).unwrap().to_string();
377 text_edit_builder.finish().apply(&mut result);
378 assert_eq_text!(ra_fixture_after, &*result);
381 if ra_fixture_after.starts_with("error:") {
382 let error_message = ra_fixture_after
385 .skip("error:".len())
386 .collect::<String>();
387 assert_eq!(error_message.trim(), err.to_string());
390 panic!("Rename to '{}' failed unexpectedly: {}", new_name, err)
396 fn check_expect(new_name: &str, ra_fixture: &str, expect: Expect) {
397 let (analysis, position) = fixture::position(ra_fixture);
398 let source_change = analysis
399 .rename(position, new_name)
401 .expect("Expect returned RangeInfo to be Some, but was None");
402 expect.assert_debug_eq(&source_change)
406 fn test_rename_to_underscore() {
407 check("_", r#"fn main() { let i<|> = 1; }"#, r#"fn main() { let _ = 1; }"#);
411 fn test_rename_to_raw_identifier() {
412 check("r#fn", r#"fn main() { let i<|> = 1; }"#, r#"fn main() { let r#fn = 1; }"#);
416 fn test_rename_to_invalid_identifier1() {
419 r#"fn main() { let i<|> = 1; }"#,
420 "error: Invalid name `invalid!`: not an identifier",
425 fn test_rename_to_invalid_identifier2() {
428 r#"fn main() { let i<|> = 1; }"#,
429 "error: Invalid name `multiple tokens`: not an identifier",
434 fn test_rename_to_invalid_identifier3() {
437 r#"fn main() { let i<|> = 1; }"#,
438 "error: Invalid name `let`: not an identifier",
443 fn test_rename_for_local() {
472 fn test_rename_unresolved_reference() {
475 r#"fn main() { let _ = unresolved_ref<|>; }"#,
476 "error: No references found at position",
481 fn test_rename_for_macro_args() {
485 macro_rules! foo {($i:ident) => {$i} }
492 macro_rules! foo {($i:ident) => {$i} }
502 fn test_rename_for_macro_args_rev() {
506 macro_rules! foo {($i:ident) => {$i} }
513 macro_rules! foo {($i:ident) => {$i} }
523 fn test_rename_for_macro_define_fn() {
527 macro_rules! define_fn {($id:ident) => { fn $id{} }}
534 macro_rules! define_fn {($id:ident) => { fn $id{} }}
544 fn test_rename_for_macro_define_fn_rev() {
548 macro_rules! define_fn {($id:ident) => { fn $id{} }}
555 macro_rules! define_fn {($id:ident) => { fn $id{} }}
565 fn test_rename_for_param_inside() {
566 check("j", r#"fn foo(i : u32) -> u32 { i<|> }"#, r#"fn foo(j : u32) -> u32 { j }"#);
570 fn test_rename_refs_for_fn_param() {
571 check("j", r#"fn foo(i<|> : u32) -> u32 { i }"#, r#"fn foo(j : u32) -> u32 { j }"#);
575 fn test_rename_for_mut_param() {
576 check("j", r#"fn foo(mut i<|> : u32) -> u32 { i }"#, r#"fn foo(mut j : u32) -> u32 { j }"#);
580 fn test_rename_struct_field() {
584 struct Foo { i<|>: i32 }
587 fn new(i: i32) -> Self {
593 struct Foo { j: i32 }
596 fn new(i: i32) -> Self {
605 fn test_rename_struct_field_for_shorthand() {
606 mark::check!(test_rename_struct_field_for_shorthand);
610 struct Foo { i<|>: i32 }
613 fn new(i: i32) -> Self {
619 struct Foo { j: i32 }
622 fn new(i: i32) -> Self {
631 fn test_rename_local_for_field_shorthand() {
632 mark::check!(test_rename_local_for_field_shorthand);
636 struct Foo { i: i32 }
639 fn new(i<|>: i32) -> Self {
645 struct Foo { i: i32 }
648 fn new(j: i32) -> Self {
657 fn test_field_shorthand_correct_struct() {
661 struct Foo { i<|>: i32 }
662 struct Bar { i: i32 }
665 fn new(i: i32) -> Self {
671 struct Foo { j: i32 }
672 struct Bar { i: i32 }
675 fn new(i: i32) -> Self {
684 fn test_shadow_local_for_struct_shorthand() {
688 struct Foo { i: i32 }
690 fn baz(i<|>: i32) -> Self {
699 struct Foo { i: i32 }
701 fn baz(j: i32) -> Self {
702 let x = Foo { i: j };
713 fn test_rename_mod() {
764 fn test_rename_mod_in_use_tree() {
774 pub struct FooContent;
777 use crate::foo<|>::FooContent;
830 fn test_rename_mod_in_dir() {
866 dst: "../foo2/mod.rs",
877 fn test_rename_unusually_nested_mod() {
882 mod outer { mod fo<|>o; }
925 fn test_module_rename_in_path() {
929 mod <|>foo { pub fn bar() {} }
931 fn main() { foo::bar(); }
934 mod baz { pub fn bar() {} }
936 fn main() { baz::bar(); }
942 fn test_rename_mod_filename_and_path() {
1009 fn test_enum_variant_from_module_1() {
1014 pub enum Foo { Bar<|> }
1017 fn func(f: foo::Foo) {
1025 pub enum Foo { Baz }
1028 fn func(f: foo::Foo) {
1038 fn test_enum_variant_from_module_2() {
1043 pub struct Foo { pub bar<|>: uint }
1046 fn foo(f: foo::Foo) {
1052 pub struct Foo { pub baz: uint }
1055 fn foo(f: foo::Foo) {
1063 fn test_parameter_to_self() {
1067 struct Foo { i: i32 }
1070 fn f(foo<|>: &mut Foo) -> i32 {
1076 struct Foo { i: i32 }
1079 fn f(&mut self) -> i32 {
1088 fn test_self_to_parameter() {
1092 struct Foo { i: i32 }
1095 fn f(&mut <|>self) -> i32 {
1101 struct Foo { i: i32 }
1104 fn f(foo: &mut Foo) -> i32 {
1113 fn test_self_in_path_to_parameter() {
1117 struct Foo { i: i32 }
1120 fn f(&self) -> i32 {
1127 struct Foo { i: i32 }
1130 fn f(foo: &Foo) -> i32 {
1140 fn test_initializer_use_field_init_shorthand() {
1141 mark::check!(test_rename_field_expr_pat);
1145 struct Foo { i<|>: i32 }
1147 fn foo(bar: i32) -> Foo {
1152 struct Foo { bar: i32 }
1154 fn foo(bar: i32) -> Foo {
1162 fn test_struct_field_destructure_into_shorthand() {
1166 struct Foo { i<|>: i32 }
1169 let Foo { i: baz } = foo;
1174 struct Foo { baz: i32 }
1177 let Foo { baz } = foo;
1185 fn test_rename_binding_in_destructure_pat() {
1186 let expected_fixture = r#"
1192 let Foo { i: bar } = foo;
1204 let Foo { i: b } = foo;
1218 let Foo { i } = foo;
1227 fn test_rename_binding_in_destructure_param_pat() {
1235 fn foo(Foo { i }: foo) -> i32 {
1244 fn foo(Foo { i: bar }: foo) -> i32 {