1 //! FIXME: write short doc here
3 use hir::{Module, ModuleDef, ModuleSource, Semantics};
4 use ide_db::base_db::{FileRange, SourceDatabaseExt};
6 defs::{Definition, NameClass, NameRefClass},
16 algo::find_node_at_offset,
17 ast::{self, NameOwner},
18 lex_single_syntax_kind, match_ast, AstNode, SyntaxKind, SyntaxNode, SyntaxToken,
21 use text_edit::TextEdit;
24 references::find_all_refs, FilePosition, FileSystemEdit, RangeInfo, Reference, ReferenceKind,
25 SourceChange, SourceFileEdit, TextRange, TextSize,
29 pub struct RenameError(pub(crate) String);
31 impl fmt::Display for RenameError {
32 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33 Display::fmt(&self.0, f)
37 impl Error for RenameError {}
41 position: FilePosition,
43 ) -> Result<RangeInfo<SourceChange>, RenameError> {
44 let sema = Semantics::new(db);
45 rename_with_semantics(&sema, position, new_name)
48 pub(crate) fn rename_with_semantics(
49 sema: &Semantics<RootDatabase>,
50 position: FilePosition,
52 ) -> Result<RangeInfo<SourceChange>, RenameError> {
53 match lex_single_syntax_kind(new_name) {
54 Some(res) => match res {
55 (SyntaxKind::IDENT, _) => (),
56 (SyntaxKind::UNDERSCORE, _) => (),
57 (SyntaxKind::SELF_KW, _) => return rename_to_self(&sema, position),
58 (_, Some(syntax_error)) => {
59 return Err(RenameError(format!("Invalid name `{}`: {}", new_name, syntax_error)))
62 return Err(RenameError(format!("Invalid name `{}`: not an identifier", new_name)))
65 None => return Err(RenameError(format!("Invalid name `{}`: not an identifier", new_name))),
68 let source_file = sema.parse(position.file_id);
69 let syntax = source_file.syntax();
70 if let Some(module) = find_module_at_offset(&sema, position, syntax) {
71 rename_mod(&sema, position, module, new_name)
72 } else if let Some(self_token) =
73 syntax.token_at_offset(position.offset).find(|t| t.kind() == SyntaxKind::SELF_KW)
75 rename_self_to_param(&sema, position, self_token, new_name)
77 rename_reference(&sema, position, new_name)
81 fn find_module_at_offset(
82 sema: &Semantics<RootDatabase>,
83 position: FilePosition,
86 let ident = syntax.token_at_offset(position.offset).find(|t| t.kind() == SyntaxKind::IDENT)?;
88 let module = match_ast! {
89 match (ident.parent()) {
90 ast::NameRef(name_ref) => {
91 match NameRefClass::classify(sema, &name_ref)? {
92 NameRefClass::Definition(Definition::ModuleDef(ModuleDef::Module(module))) => module,
97 match NameClass::classify(&sema, &name)? {
98 NameClass::Definition(Definition::ModuleDef(ModuleDef::Module(module))) => module,
109 fn source_edit_from_reference(
110 sema: &Semantics<RootDatabase>,
111 reference: Reference,
113 ) -> SourceFileEdit {
114 let mut replacement_text = String::new();
115 let range = match reference.kind {
116 ReferenceKind::FieldShorthandForField => {
117 mark::hit!(test_rename_struct_field_for_shorthand);
118 replacement_text.push_str(new_name);
119 replacement_text.push_str(": ");
120 TextRange::new(reference.file_range.range.start(), reference.file_range.range.start())
122 ReferenceKind::FieldShorthandForLocal => {
123 mark::hit!(test_rename_local_for_field_shorthand);
124 replacement_text.push_str(": ");
125 replacement_text.push_str(new_name);
126 TextRange::new(reference.file_range.range.end(), reference.file_range.range.end())
128 ReferenceKind::RecordFieldExprOrPat => {
129 mark::hit!(test_rename_field_expr_pat);
130 replacement_text.push_str(new_name);
131 edit_text_range_for_record_field_expr_or_pat(sema, reference.file_range, new_name)
134 replacement_text.push_str(new_name);
135 reference.file_range.range
139 file_id: reference.file_range.file_id,
140 edit: TextEdit::replace(range, replacement_text),
144 fn edit_text_range_for_record_field_expr_or_pat(
145 sema: &Semantics<RootDatabase>,
146 file_range: FileRange,
149 let source_file = sema.parse(file_range.file_id);
150 let file_syntax = source_file.syntax();
151 let original_range = file_range.range;
153 syntax::algo::find_node_at_range::<ast::RecordExprField>(file_syntax, original_range)
154 .and_then(|field_expr| match field_expr.expr().and_then(|e| e.name_ref()) {
155 Some(name) if &name.to_string() == new_name => Some(field_expr.syntax().text_range()),
159 syntax::algo::find_node_at_range::<ast::RecordPatField>(file_syntax, original_range)
160 .and_then(|field_pat| match field_pat.pat() {
161 Some(ast::Pat::IdentPat(pat))
162 if pat.name().map(|n| n.to_string()).as_deref() == Some(new_name) =>
164 Some(field_pat.syntax().text_range())
169 .unwrap_or(original_range)
173 sema: &Semantics<RootDatabase>,
174 position: FilePosition,
177 ) -> Result<RangeInfo<SourceChange>, RenameError> {
178 let mut source_file_edits = Vec::new();
179 let mut file_system_edits = Vec::new();
181 let src = module.definition_source(sema.db);
182 let file_id = src.file_id.original_file(sema.db);
184 ModuleSource::SourceFile(..) => {
185 // mod is defined in path/to/dir/mod.rs
186 let dst = if module.is_mod_rs(sema.db) {
187 format!("../{}/mod.rs", new_name)
189 format!("{}.rs", new_name)
191 let move_file = FileSystemEdit::MoveFile { src: file_id, anchor: 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 = find_node_at_offset::<ast::Fn>(syn, position.offset)
226 .ok_or_else(|| RenameError("No surrounding method declaration found".to_string()))?;
228 fn_def.param_list().ok_or_else(|| RenameError("Method has no parameters".to_string()))?;
229 if params.self_param().is_some() {
230 return Err(RenameError("Method already has a self parameter".to_string()));
233 params.params().next().ok_or_else(|| RenameError("Method has no parameters".into()))?;
234 let mutable = match first_param.ty() {
235 Some(ast::Type::RefType(rt)) => rt.mut_token().is_some(),
236 _ => return Err(RenameError("Not renaming other types".to_string())),
239 let RangeInfo { range, info: refs } = find_all_refs(sema, position, None)
240 .ok_or_else(|| RenameError("No reference found at position".to_string()))?;
242 let param_range = first_param.syntax().text_range();
243 let (param_ref, usages): (Vec<Reference>, Vec<Reference>) = refs
245 .partition(|reference| param_range.intersect(reference.file_range.range).is_some());
247 if param_ref.is_empty() {
248 return Err(RenameError("Parameter to rename not found".to_string()));
251 let mut edits = usages
253 .map(|reference| source_edit_from_reference(sema, reference, "self"))
254 .collect::<Vec<_>>();
256 edits.push(SourceFileEdit {
257 file_id: position.file_id,
258 edit: TextEdit::replace(
260 String::from(if mutable { "&mut self" } else { "&self" }),
264 Ok(RangeInfo::new(range, SourceChange::from(edits)))
267 fn text_edit_from_self_param(
269 self_param: &ast::SelfParam,
271 ) -> Option<TextEdit> {
272 fn target_type_name(impl_def: &ast::Impl) -> Option<String> {
273 if let Some(ast::Type::PathType(p)) = impl_def.self_ty() {
274 return Some(p.path()?.segment()?.name_ref()?.text().to_string());
279 let impl_def = find_node_at_offset::<ast::Impl>(syn, self_param.syntax().text_range().start())?;
280 let type_name = target_type_name(&impl_def)?;
282 let mut replacement_text = String::from(new_name);
283 replacement_text.push_str(": ");
284 replacement_text.push_str(self_param.mut_token().map_or("&", |_| "&mut "));
285 replacement_text.push_str(type_name.as_str());
287 Some(TextEdit::replace(self_param.syntax().text_range(), replacement_text))
290 fn rename_self_to_param(
291 sema: &Semantics<RootDatabase>,
292 position: FilePosition,
293 self_token: SyntaxToken,
295 ) -> Result<RangeInfo<SourceChange>, RenameError> {
296 let source_file = sema.parse(position.file_id);
297 let syn = source_file.syntax();
299 let text = sema.db.file_text(position.file_id);
300 let fn_def = find_node_at_offset::<ast::Fn>(syn, position.offset)
301 .ok_or_else(|| RenameError("No surrounding method declaration found".to_string()))?;
302 let search_range = fn_def.syntax().text_range();
304 let mut edits: Vec<SourceFileEdit> = vec![];
306 for (idx, _) in text.match_indices("self") {
307 let offset: TextSize = idx.try_into().unwrap();
308 if !search_range.contains_inclusive(offset) {
311 if let Some(ref usage) =
312 syn.token_at_offset(offset).find(|t| t.kind() == SyntaxKind::SELF_KW)
314 let edit = if let Some(ref self_param) = ast::SelfParam::cast(usage.parent()) {
315 text_edit_from_self_param(syn, self_param, new_name)
316 .ok_or_else(|| RenameError("No target type found".to_string()))?
318 TextEdit::replace(usage.text_range(), String::from(new_name))
320 edits.push(SourceFileEdit { file_id: position.file_id, edit });
324 let range = ast::SelfParam::cast(self_token.parent())
325 .map_or(self_token.text_range(), |p| p.syntax().text_range());
327 Ok(RangeInfo::new(range, SourceChange::from(edits)))
331 sema: &Semantics<RootDatabase>,
332 position: FilePosition,
334 ) -> Result<RangeInfo<SourceChange>, RenameError> {
335 let RangeInfo { range, info: refs } = match find_all_refs(sema, position, None) {
336 Some(range_info) => range_info,
337 None => return Err(RenameError("No references found at position".to_string())),
342 .map(|reference| source_edit_from_reference(sema, reference, new_name))
343 .collect::<Vec<_>>();
346 return Err(RenameError("No references found at position".to_string()));
349 Ok(RangeInfo::new(range, SourceChange::from(edit)))
354 use expect_test::{expect, Expect};
355 use stdx::trim_indent;
356 use test_utils::{assert_eq_text, mark};
357 use text_edit::TextEdit;
359 use crate::{fixture, FileId};
361 fn check(new_name: &str, ra_fixture_before: &str, ra_fixture_after: &str) {
362 let ra_fixture_after = &trim_indent(ra_fixture_after);
363 let (analysis, position) = fixture::position(ra_fixture_before);
364 let rename_result = analysis
365 .rename(position, new_name)
366 .unwrap_or_else(|err| panic!("Rename to '{}' was cancelled: {}", new_name, err));
367 match rename_result {
368 Ok(source_change) => {
369 let mut text_edit_builder = TextEdit::builder();
370 let mut file_id: Option<FileId> = None;
371 for edit in source_change.info.source_file_edits {
372 file_id = Some(edit.file_id);
373 for indel in edit.edit.into_iter() {
374 text_edit_builder.replace(indel.delete, indel.insert);
377 let mut result = analysis.file_text(file_id.unwrap()).unwrap().to_string();
378 text_edit_builder.finish().apply(&mut result);
379 assert_eq_text!(ra_fixture_after, &*result);
382 if ra_fixture_after.starts_with("error:") {
383 let error_message = ra_fixture_after
386 .skip("error:".len())
387 .collect::<String>();
388 assert_eq!(error_message.trim(), err.to_string());
391 panic!("Rename to '{}' failed unexpectedly: {}", new_name, err)
397 fn check_expect(new_name: &str, ra_fixture: &str, expect: Expect) {
398 let (analysis, position) = fixture::position(ra_fixture);
399 let source_change = analysis
400 .rename(position, new_name)
402 .expect("Expect returned RangeInfo to be Some, but was None");
403 expect.assert_debug_eq(&source_change)
407 fn test_rename_to_underscore() {
408 check("_", r#"fn main() { let i<|> = 1; }"#, r#"fn main() { let _ = 1; }"#);
412 fn test_rename_to_raw_identifier() {
413 check("r#fn", r#"fn main() { let i<|> = 1; }"#, r#"fn main() { let r#fn = 1; }"#);
417 fn test_rename_to_invalid_identifier1() {
420 r#"fn main() { let i<|> = 1; }"#,
421 "error: Invalid name `invalid!`: not an identifier",
426 fn test_rename_to_invalid_identifier2() {
429 r#"fn main() { let i<|> = 1; }"#,
430 "error: Invalid name `multiple tokens`: not an identifier",
435 fn test_rename_to_invalid_identifier3() {
438 r#"fn main() { let i<|> = 1; }"#,
439 "error: Invalid name `let`: not an identifier",
444 fn test_rename_for_local() {
473 fn test_rename_unresolved_reference() {
476 r#"fn main() { let _ = unresolved_ref<|>; }"#,
477 "error: No references found at position",
482 fn test_rename_for_macro_args() {
486 macro_rules! foo {($i:ident) => {$i} }
493 macro_rules! foo {($i:ident) => {$i} }
503 fn test_rename_for_macro_args_rev() {
507 macro_rules! foo {($i:ident) => {$i} }
514 macro_rules! foo {($i:ident) => {$i} }
524 fn test_rename_for_macro_define_fn() {
528 macro_rules! define_fn {($id:ident) => { fn $id{} }}
535 macro_rules! define_fn {($id:ident) => { fn $id{} }}
545 fn test_rename_for_macro_define_fn_rev() {
549 macro_rules! define_fn {($id:ident) => { fn $id{} }}
556 macro_rules! define_fn {($id:ident) => { fn $id{} }}
566 fn test_rename_for_param_inside() {
567 check("j", r#"fn foo(i : u32) -> u32 { i<|> }"#, r#"fn foo(j : u32) -> u32 { j }"#);
571 fn test_rename_refs_for_fn_param() {
572 check("j", r#"fn foo(i<|> : u32) -> u32 { i }"#, r#"fn foo(j : u32) -> u32 { j }"#);
576 fn test_rename_for_mut_param() {
577 check("j", r#"fn foo(mut i<|> : u32) -> u32 { i }"#, r#"fn foo(mut j : u32) -> u32 { j }"#);
581 fn test_rename_struct_field() {
585 struct Foo { i<|>: i32 }
588 fn new(i: i32) -> Self {
594 struct Foo { j: i32 }
597 fn new(i: i32) -> Self {
606 fn test_rename_struct_field_for_shorthand() {
607 mark::check!(test_rename_struct_field_for_shorthand);
611 struct Foo { i<|>: i32 }
614 fn new(i: i32) -> Self {
620 struct Foo { j: i32 }
623 fn new(i: i32) -> Self {
632 fn test_rename_local_for_field_shorthand() {
633 mark::check!(test_rename_local_for_field_shorthand);
637 struct Foo { i: i32 }
640 fn new(i<|>: i32) -> Self {
646 struct Foo { i: i32 }
649 fn new(j: i32) -> Self {
658 fn test_field_shorthand_correct_struct() {
662 struct Foo { i<|>: i32 }
663 struct Bar { i: i32 }
666 fn new(i: i32) -> Self {
672 struct Foo { j: i32 }
673 struct Bar { i: i32 }
676 fn new(i: i32) -> Self {
685 fn test_shadow_local_for_struct_shorthand() {
689 struct Foo { i: i32 }
691 fn baz(i<|>: i32) -> Self {
700 struct Foo { i: i32 }
702 fn baz(j: i32) -> Self {
703 let x = Foo { i: j };
714 fn test_rename_mod() {
765 fn test_rename_mod_in_use_tree() {
775 pub struct FooContent;
778 use crate::foo<|>::FooContent;
831 fn test_rename_mod_in_dir() {
867 dst: "../foo2/mod.rs",
878 fn test_rename_unusually_nested_mod() {
883 mod outer { mod fo<|>o; }
926 fn test_module_rename_in_path() {
930 mod <|>foo { pub fn bar() {} }
932 fn main() { foo::bar(); }
935 mod baz { pub fn bar() {} }
937 fn main() { baz::bar(); }
943 fn test_rename_mod_filename_and_path() {
1010 fn test_enum_variant_from_module_1() {
1015 pub enum Foo { Bar<|> }
1018 fn func(f: foo::Foo) {
1026 pub enum Foo { Baz }
1029 fn func(f: foo::Foo) {
1039 fn test_enum_variant_from_module_2() {
1044 pub struct Foo { pub bar<|>: uint }
1047 fn foo(f: foo::Foo) {
1053 pub struct Foo { pub baz: uint }
1056 fn foo(f: foo::Foo) {
1064 fn test_parameter_to_self() {
1068 struct Foo { i: i32 }
1071 fn f(foo<|>: &mut Foo) -> i32 {
1077 struct Foo { i: i32 }
1080 fn f(&mut self) -> i32 {
1089 fn test_self_to_parameter() {
1093 struct Foo { i: i32 }
1096 fn f(&mut <|>self) -> i32 {
1102 struct Foo { i: i32 }
1105 fn f(foo: &mut Foo) -> i32 {
1114 fn test_self_in_path_to_parameter() {
1118 struct Foo { i: i32 }
1121 fn f(&self) -> i32 {
1128 struct Foo { i: i32 }
1131 fn f(foo: &Foo) -> i32 {
1141 fn test_initializer_use_field_init_shorthand() {
1142 mark::check!(test_rename_field_expr_pat);
1146 struct Foo { i<|>: i32 }
1148 fn foo(bar: i32) -> Foo {
1153 struct Foo { bar: i32 }
1155 fn foo(bar: i32) -> Foo {
1163 fn test_struct_field_destructure_into_shorthand() {
1167 struct Foo { i<|>: i32 }
1170 let Foo { i: baz } = foo;
1175 struct Foo { baz: i32 }
1178 let Foo { baz } = foo;
1186 fn test_rename_binding_in_destructure_pat() {
1187 let expected_fixture = r#"
1193 let Foo { i: bar } = foo;
1205 let Foo { i: b } = foo;
1219 let Foo { i } = foo;
1228 fn test_rename_binding_in_destructure_param_pat() {
1236 fn foo(Foo { i }: foo) -> i32 {
1245 fn foo(Foo { i: bar }: foo) -> i32 {