aboutsummaryrefslogtreecommitdiff
path: root/crates
diff options
context:
space:
mode:
authorAleksey Kladov <[email protected]>2021-06-14 16:46:27 +0100
committerAleksey Kladov <[email protected]>2021-06-14 16:46:54 +0100
commit26c978f258ed2af45a6979eefea9860c1eaeacda (patch)
tree6b96b1d2f5ba48148dcfd6442ab9c742696e7847 /crates
parenta91071b57be6e64ad2fd277998ada0ae6206457b (diff)
internal: adapt diagnostics to the new rename API
Diffstat (limited to 'crates')
-rw-r--r--crates/ide/src/references/rename.rs435
-rw-r--r--crates/ide_db/src/lib.rs4
-rw-r--r--crates/ide_db/src/rename.rs444
-rw-r--r--crates/ide_diagnostics/src/incorrect_case.rs46
4 files changed, 474 insertions, 455 deletions
diff --git a/crates/ide/src/references/rename.rs b/crates/ide/src/references/rename.rs
index 6b3d02bf4..88b6b1260 100644
--- a/crates/ide/src/references/rename.rs
+++ b/crates/ide/src/references/rename.rs
@@ -2,44 +2,23 @@
2//! 2//!
3//! All reference and file rename requests go through here where the corresponding [`SourceChange`]s 3//! All reference and file rename requests go through here where the corresponding [`SourceChange`]s
4//! will be calculated. 4//! will be calculated.
5use std::fmt::{self, Display}; 5use hir::{AsAssocItem, InFile, Semantics};
6
7use either::Either;
8use hir::{AsAssocItem, FieldSource, HasSource, InFile, ModuleSource, Semantics};
9use ide_db::{ 6use ide_db::{
10 base_db::{AnchoredPathBuf, FileId, FileRange}, 7 base_db::FileId,
11 defs::{Definition, NameClass, NameRefClass}, 8 defs::{Definition, NameClass, NameRefClass},
12 search::FileReference, 9 rename::{bail, format_err, source_edit_from_references, IdentifierKind},
13 RootDatabase, 10 RootDatabase,
14}; 11};
15use stdx::never; 12use stdx::never;
16use syntax::{ 13use syntax::{ast, AstNode, SyntaxNode};
17 ast::{self, NameOwner},
18 lex_single_syntax_kind, AstNode, SyntaxKind, SyntaxNode, T,
19};
20 14
21use text_edit::TextEdit; 15use text_edit::TextEdit;
22 16
23use crate::{FilePosition, FileSystemEdit, RangeInfo, SourceChange, TextRange}; 17use crate::{FilePosition, RangeInfo, SourceChange};
24
25type RenameResult<T> = Result<T, RenameError>;
26#[derive(Debug)]
27pub struct RenameError(String);
28
29impl fmt::Display for RenameError {
30 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31 Display::fmt(&self.0, f)
32 }
33}
34 18
35macro_rules! format_err { 19pub use ide_db::rename::RenameError;
36 ($fmt:expr) => {RenameError(format!($fmt))};
37 ($fmt:expr, $($arg:tt)+) => {RenameError(format!($fmt, $($arg)+))}
38}
39 20
40macro_rules! bail { 21type RenameResult<T> = Result<T, RenameError>;
41 ($($tokens:tt)*) => {return Err(format_err!($($tokens)*))}
42}
43 22
44/// Prepares a rename. The sole job of this function is to return the TextRange of the thing that is 23/// Prepares a rename. The sole job of this function is to return the TextRange of the thing that is
45/// being targeted for a rename. 24/// being targeted for a rename.
@@ -52,8 +31,8 @@ pub(crate) fn prepare_rename(
52 let syntax = source_file.syntax(); 31 let syntax = source_file.syntax();
53 32
54 let def = find_definition(&sema, syntax, position)?; 33 let def = find_definition(&sema, syntax, position)?;
55 let frange = def_name_range(&&sema, def) 34 let frange =
56 .ok_or_else(|| format_err!("No references found at position"))?; 35 def.rename_range(&sema).ok_or_else(|| format_err!("No references found at position"))?;
57 Ok(RangeInfo::new(frange.range, ())) 36 Ok(RangeInfo::new(frange.range, ()))
58} 37}
59 38
@@ -98,14 +77,7 @@ pub(crate) fn rename_with_semantics(
98 } 77 }
99 } 78 }
100 79
101 match def { 80 def.rename(sema, new_name)
102 Definition::ModuleDef(hir::ModuleDef::Module(module)) => rename_mod(sema, module, new_name),
103 Definition::SelfType(_) => bail!("Cannot rename `Self`"),
104 Definition::ModuleDef(hir::ModuleDef::BuiltinType(_)) => {
105 bail!("Cannot rename builtin type")
106 }
107 def => rename_reference(sema, def, new_name),
108 }
109} 81}
110 82
111/// Called by the client when it is about to rename a file. 83/// Called by the client when it is about to rename a file.
@@ -116,38 +88,12 @@ pub(crate) fn will_rename_file(
116) -> Option<SourceChange> { 88) -> Option<SourceChange> {
117 let sema = Semantics::new(db); 89 let sema = Semantics::new(db);
118 let module = sema.to_module_def(file_id)?; 90 let module = sema.to_module_def(file_id)?;
119 let mut change = rename_mod(&sema, module, new_name_stem).ok()?; 91 let def = Definition::ModuleDef(module.into());
92 let mut change = def.rename(&sema, new_name_stem).ok()?;
120 change.file_system_edits.clear(); 93 change.file_system_edits.clear();
121 Some(change) 94 Some(change)
122} 95}
123 96
124#[derive(Copy, Clone, Debug, PartialEq)]
125enum IdentifierKind {
126 Ident,
127 Lifetime,
128 Underscore,
129}
130
131impl IdentifierKind {
132 fn classify(new_name: &str) -> RenameResult<IdentifierKind> {
133 match lex_single_syntax_kind(new_name) {
134 Some(res) => match res {
135 (SyntaxKind::IDENT, _) => Ok(IdentifierKind::Ident),
136 (T![_], _) => Ok(IdentifierKind::Underscore),
137 (SyntaxKind::LIFETIME_IDENT, _) if new_name != "'static" && new_name != "'_" => {
138 Ok(IdentifierKind::Lifetime)
139 }
140 (SyntaxKind::LIFETIME_IDENT, _) => {
141 bail!("Invalid name `{}`: not a lifetime identifier", new_name)
142 }
143 (_, Some(syntax_error)) => bail!("Invalid name `{}`: {}", new_name, syntax_error),
144 (_, None) => bail!("Invalid name `{}`: not an identifier", new_name),
145 },
146 None => bail!("Invalid name `{}`: not an identifier", new_name),
147 }
148 }
149}
150
151fn find_definition( 97fn find_definition(
152 sema: &Semantics<RootDatabase>, 98 sema: &Semantics<RootDatabase>,
153 syntax: &SyntaxNode, 99 syntax: &SyntaxNode,
@@ -189,126 +135,6 @@ fn find_definition(
189 .ok_or_else(|| format_err!("No references found at position")) 135 .ok_or_else(|| format_err!("No references found at position"))
190} 136}
191 137
192fn rename_mod(
193 sema: &Semantics<RootDatabase>,
194 module: hir::Module,
195 new_name: &str,
196) -> RenameResult<SourceChange> {
197 if IdentifierKind::classify(new_name)? != IdentifierKind::Ident {
198 bail!("Invalid name `{0}`: cannot rename module to {0}", new_name);
199 }
200
201 let mut source_change = SourceChange::default();
202
203 let InFile { file_id, value: def_source } = module.definition_source(sema.db);
204 let file_id = file_id.original_file(sema.db);
205 if let ModuleSource::SourceFile(..) = def_source {
206 // mod is defined in path/to/dir/mod.rs
207 let path = if module.is_mod_rs(sema.db) {
208 format!("../{}/mod.rs", new_name)
209 } else {
210 format!("{}.rs", new_name)
211 };
212 let dst = AnchoredPathBuf { anchor: file_id, path };
213 let move_file = FileSystemEdit::MoveFile { src: file_id, dst };
214 source_change.push_file_system_edit(move_file);
215 }
216
217 if let Some(InFile { file_id, value: decl_source }) = module.declaration_source(sema.db) {
218 let file_id = file_id.original_file(sema.db);
219 match decl_source.name() {
220 Some(name) => source_change.insert_source_edit(
221 file_id,
222 TextEdit::replace(name.syntax().text_range(), new_name.to_string()),
223 ),
224 _ => never!("Module source node is missing a name"),
225 }
226 }
227 let def = Definition::ModuleDef(hir::ModuleDef::Module(module));
228 let usages = def.usages(sema).all();
229 let ref_edits = usages.iter().map(|(&file_id, references)| {
230 (file_id, source_edit_from_references(references, def, new_name))
231 });
232 source_change.extend(ref_edits);
233
234 Ok(source_change)
235}
236
237fn rename_reference(
238 sema: &Semantics<RootDatabase>,
239 mut def: Definition,
240 new_name: &str,
241) -> RenameResult<SourceChange> {
242 let ident_kind = IdentifierKind::classify(new_name)?;
243
244 if matches!(
245 def, // is target a lifetime?
246 Definition::GenericParam(hir::GenericParam::LifetimeParam(_)) | Definition::Label(_)
247 ) {
248 match ident_kind {
249 IdentifierKind::Ident | IdentifierKind::Underscore => {
250 cov_mark::hit!(rename_not_a_lifetime_ident_ref);
251 bail!("Invalid name `{}`: not a lifetime identifier", new_name);
252 }
253 IdentifierKind::Lifetime => cov_mark::hit!(rename_lifetime),
254 }
255 } else {
256 match (ident_kind, def) {
257 (IdentifierKind::Lifetime, _) => {
258 cov_mark::hit!(rename_not_an_ident_ref);
259 bail!("Invalid name `{}`: not an identifier", new_name);
260 }
261 (IdentifierKind::Ident, _) => cov_mark::hit!(rename_non_local),
262 (IdentifierKind::Underscore, _) => (),
263 }
264 }
265
266 def = match def {
267 // HACK: resolve trait impl items to the item def of the trait definition
268 // so that we properly resolve all trait item references
269 Definition::ModuleDef(mod_def) => mod_def
270 .as_assoc_item(sema.db)
271 .and_then(|it| it.containing_trait_impl(sema.db))
272 .and_then(|it| {
273 it.items(sema.db).into_iter().find_map(|it| match (it, mod_def) {
274 (hir::AssocItem::Function(trait_func), hir::ModuleDef::Function(func))
275 if trait_func.name(sema.db) == func.name(sema.db) =>
276 {
277 Some(Definition::ModuleDef(hir::ModuleDef::Function(trait_func)))
278 }
279 (hir::AssocItem::Const(trait_konst), hir::ModuleDef::Const(konst))
280 if trait_konst.name(sema.db) == konst.name(sema.db) =>
281 {
282 Some(Definition::ModuleDef(hir::ModuleDef::Const(trait_konst)))
283 }
284 (
285 hir::AssocItem::TypeAlias(trait_type_alias),
286 hir::ModuleDef::TypeAlias(type_alias),
287 ) if trait_type_alias.name(sema.db) == type_alias.name(sema.db) => {
288 Some(Definition::ModuleDef(hir::ModuleDef::TypeAlias(trait_type_alias)))
289 }
290 _ => None,
291 })
292 })
293 .unwrap_or(def),
294 _ => def,
295 };
296 let usages = def.usages(sema).all();
297
298 if !usages.is_empty() && ident_kind == IdentifierKind::Underscore {
299 cov_mark::hit!(rename_underscore_multiple);
300 bail!("Cannot rename reference to `_` as it is being referenced multiple times");
301 }
302 let mut source_change = SourceChange::default();
303 source_change.extend(usages.iter().map(|(&file_id, references)| {
304 (file_id, source_edit_from_references(references, def, new_name))
305 }));
306
307 let (file_id, edit) = source_edit_from_def(sema, def, new_name)?;
308 source_change.insert_source_edit(file_id, edit);
309 Ok(source_change)
310}
311
312fn rename_to_self(sema: &Semantics<RootDatabase>, local: hir::Local) -> RenameResult<SourceChange> { 138fn rename_to_self(sema: &Semantics<RootDatabase>, local: hir::Local) -> RenameResult<SourceChange> {
313 if never!(local.is_self(sema.db)) { 139 if never!(local.is_self(sema.db)) {
314 bail!("rename_to_self invoked on self"); 140 bail!("rename_to_self invoked on self");
@@ -426,243 +252,6 @@ fn text_edit_from_self_param(self_param: &ast::SelfParam, new_name: &str) -> Opt
426 Some(TextEdit::replace(self_param.syntax().text_range(), replacement_text)) 252 Some(TextEdit::replace(self_param.syntax().text_range(), replacement_text))
427} 253}
428 254
429fn source_edit_from_references(
430 references: &[FileReference],
431 def: Definition,
432 new_name: &str,
433) -> TextEdit {
434 let mut edit = TextEdit::builder();
435 for reference in references {
436 let (range, replacement) = match &reference.name {
437 // if the ranges differ then the node is inside a macro call, we can't really attempt
438 // to make special rewrites like shorthand syntax and such, so just rename the node in
439 // the macro input
440 ast::NameLike::NameRef(name_ref)
441 if name_ref.syntax().text_range() == reference.range =>
442 {
443 source_edit_from_name_ref(name_ref, new_name, def)
444 }
445 ast::NameLike::Name(name) if name.syntax().text_range() == reference.range => {
446 source_edit_from_name(name, new_name)
447 }
448 _ => None,
449 }
450 .unwrap_or_else(|| (reference.range, new_name.to_string()));
451 edit.replace(range, replacement);
452 }
453 edit.finish()
454}
455
456fn source_edit_from_name(name: &ast::Name, new_name: &str) -> Option<(TextRange, String)> {
457 if let Some(_) = ast::RecordPatField::for_field_name(name) {
458 if let Some(ident_pat) = name.syntax().parent().and_then(ast::IdentPat::cast) {
459 return Some((
460 TextRange::empty(ident_pat.syntax().text_range().start()),
461 [new_name, ": "].concat(),
462 ));
463 }
464 }
465 None
466}
467
468fn source_edit_from_name_ref(
469 name_ref: &ast::NameRef,
470 new_name: &str,
471 def: Definition,
472) -> Option<(TextRange, String)> {
473 if let Some(record_field) = ast::RecordExprField::for_name_ref(name_ref) {
474 let rcf_name_ref = record_field.name_ref();
475 let rcf_expr = record_field.expr();
476 match (rcf_name_ref, rcf_expr.and_then(|it| it.name_ref())) {
477 // field: init-expr, check if we can use a field init shorthand
478 (Some(field_name), Some(init)) => {
479 if field_name == *name_ref {
480 if init.text() == new_name {
481 cov_mark::hit!(test_rename_field_put_init_shorthand);
482 // same names, we can use a shorthand here instead.
483 // we do not want to erase attributes hence this range start
484 let s = field_name.syntax().text_range().start();
485 let e = record_field.syntax().text_range().end();
486 return Some((TextRange::new(s, e), new_name.to_owned()));
487 }
488 } else if init == *name_ref {
489 if field_name.text() == new_name {
490 cov_mark::hit!(test_rename_local_put_init_shorthand);
491 // same names, we can use a shorthand here instead.
492 // we do not want to erase attributes hence this range start
493 let s = field_name.syntax().text_range().start();
494 let e = record_field.syntax().text_range().end();
495 return Some((TextRange::new(s, e), new_name.to_owned()));
496 }
497 }
498 None
499 }
500 // init shorthand
501 // FIXME: instead of splitting the shorthand, recursively trigger a rename of the
502 // other name https://github.com/rust-analyzer/rust-analyzer/issues/6547
503 (None, Some(_)) if matches!(def, Definition::Field(_)) => {
504 cov_mark::hit!(test_rename_field_in_field_shorthand);
505 let s = name_ref.syntax().text_range().start();
506 Some((TextRange::empty(s), format!("{}: ", new_name)))
507 }
508 (None, Some(_)) if matches!(def, Definition::Local(_)) => {
509 cov_mark::hit!(test_rename_local_in_field_shorthand);
510 let s = name_ref.syntax().text_range().end();
511 Some((TextRange::empty(s), format!(": {}", new_name)))
512 }
513 _ => None,
514 }
515 } else if let Some(record_field) = ast::RecordPatField::for_field_name_ref(name_ref) {
516 let rcf_name_ref = record_field.name_ref();
517 let rcf_pat = record_field.pat();
518 match (rcf_name_ref, rcf_pat) {
519 // field: rename
520 (Some(field_name), Some(ast::Pat::IdentPat(pat))) if field_name == *name_ref => {
521 // field name is being renamed
522 if pat.name().map_or(false, |it| it.text() == new_name) {
523 cov_mark::hit!(test_rename_field_put_init_shorthand_pat);
524 // same names, we can use a shorthand here instead/
525 // we do not want to erase attributes hence this range start
526 let s = field_name.syntax().text_range().start();
527 let e = record_field.syntax().text_range().end();
528 Some((TextRange::new(s, e), pat.to_string()))
529 } else {
530 None
531 }
532 }
533 _ => None,
534 }
535 } else {
536 None
537 }
538}
539
540fn source_edit_from_def(
541 sema: &Semantics<RootDatabase>,
542 def: Definition,
543 new_name: &str,
544) -> RenameResult<(FileId, TextEdit)> {
545 let frange: FileRange = def_name_range(sema, def)
546 .ok_or_else(|| format_err!("No identifier available to rename"))?;
547
548 let mut replacement_text = String::new();
549 let mut repl_range = frange.range;
550 if let Definition::Local(local) = def {
551 if let Either::Left(pat) = local.source(sema.db).value {
552 if matches!(
553 pat.syntax().parent().and_then(ast::RecordPatField::cast),
554 Some(pat_field) if pat_field.name_ref().is_none()
555 ) {
556 replacement_text.push_str(": ");
557 replacement_text.push_str(new_name);
558 repl_range = TextRange::new(
559 pat.syntax().text_range().end(),
560 pat.syntax().text_range().end(),
561 );
562 }
563 }
564 }
565 if replacement_text.is_empty() {
566 replacement_text.push_str(new_name);
567 }
568 let edit = TextEdit::replace(repl_range, replacement_text);
569 Ok((frange.file_id, edit))
570}
571
572fn def_name_range(sema: &Semantics<RootDatabase>, def: Definition) -> Option<FileRange> {
573 // FIXME: the `original_file_range` calls here are wrong -- they never fail,
574 // and _fall back_ to the entirety of the macro call. Such fall back is
575 // incorrect for renames. The safe behavior would be to return an error for
576 // such cases. The correct behavior would be to return an auxiliary list of
577 // "can't rename these occurrences in macros" items, and then show some kind
578 // of a dialog to the user.
579
580 let res = match def {
581 Definition::Macro(mac) => {
582 let src = mac.source(sema.db)?;
583 let name = match &src.value {
584 Either::Left(it) => it.name()?,
585 Either::Right(it) => it.name()?,
586 };
587 src.with_value(name.syntax()).original_file_range(sema.db)
588 }
589 Definition::Field(field) => {
590 let src = field.source(sema.db)?;
591
592 match &src.value {
593 FieldSource::Named(record_field) => {
594 let name = record_field.name()?;
595 src.with_value(name.syntax()).original_file_range(sema.db)
596 }
597 FieldSource::Pos(_) => {
598 return None;
599 }
600 }
601 }
602 Definition::ModuleDef(module_def) => match module_def {
603 hir::ModuleDef::Module(module) => {
604 let src = module.declaration_source(sema.db)?;
605 let name = src.value.name()?;
606 src.with_value(name.syntax()).original_file_range(sema.db)
607 }
608 hir::ModuleDef::Function(it) => name_range(it, sema)?,
609 hir::ModuleDef::Adt(adt) => match adt {
610 hir::Adt::Struct(it) => name_range(it, sema)?,
611 hir::Adt::Union(it) => name_range(it, sema)?,
612 hir::Adt::Enum(it) => name_range(it, sema)?,
613 },
614 hir::ModuleDef::Variant(it) => name_range(it, sema)?,
615 hir::ModuleDef::Const(it) => name_range(it, sema)?,
616 hir::ModuleDef::Static(it) => name_range(it, sema)?,
617 hir::ModuleDef::Trait(it) => name_range(it, sema)?,
618 hir::ModuleDef::TypeAlias(it) => name_range(it, sema)?,
619 hir::ModuleDef::BuiltinType(_) => return None,
620 },
621 Definition::SelfType(_) => return None,
622 Definition::Local(local) => {
623 let src = local.source(sema.db);
624 let name = match &src.value {
625 Either::Left(bind_pat) => bind_pat.name()?,
626 Either::Right(_) => return None,
627 };
628 src.with_value(name.syntax()).original_file_range(sema.db)
629 }
630 Definition::GenericParam(generic_param) => match generic_param {
631 hir::GenericParam::TypeParam(type_param) => {
632 let src = type_param.source(sema.db)?;
633 let name = match &src.value {
634 Either::Left(_) => return None,
635 Either::Right(type_param) => type_param.name()?,
636 };
637 src.with_value(name.syntax()).original_file_range(sema.db)
638 }
639 hir::GenericParam::LifetimeParam(lifetime_param) => {
640 let src = lifetime_param.source(sema.db)?;
641 let lifetime = src.value.lifetime()?;
642 src.with_value(lifetime.syntax()).original_file_range(sema.db)
643 }
644 hir::GenericParam::ConstParam(it) => name_range(it, sema)?,
645 },
646 Definition::Label(label) => {
647 let src = label.source(sema.db);
648 let lifetime = src.value.lifetime()?;
649 src.with_value(lifetime.syntax()).original_file_range(sema.db)
650 }
651 };
652 return Some(res);
653
654 fn name_range<D>(def: D, sema: &Semantics<RootDatabase>) -> Option<FileRange>
655 where
656 D: HasSource,
657 D::Ast: ast::NameOwner,
658 {
659 let src = def.source(sema.db)?;
660 let name = src.value.name()?;
661 let res = src.with_value(name.syntax()).original_file_range(sema.db);
662 Some(res)
663 }
664}
665
666#[cfg(test)] 255#[cfg(test)]
667mod tests { 256mod tests {
668 use expect_test::{expect, Expect}; 257 use expect_test::{expect, Expect};
diff --git a/crates/ide_db/src/lib.rs b/crates/ide_db/src/lib.rs
index 2ac215c06..7bbd08d6f 100644
--- a/crates/ide_db/src/lib.rs
+++ b/crates/ide_db/src/lib.rs
@@ -8,7 +8,6 @@ pub mod label;
8pub mod line_index; 8pub mod line_index;
9pub mod symbol_index; 9pub mod symbol_index;
10pub mod defs; 10pub mod defs;
11pub mod search;
12pub mod items_locator; 11pub mod items_locator;
13pub mod source_change; 12pub mod source_change;
14pub mod ty_filter; 13pub mod ty_filter;
@@ -16,6 +15,9 @@ pub mod traits;
16pub mod call_info; 15pub mod call_info;
17pub mod helpers; 16pub mod helpers;
18 17
18pub mod search;
19pub mod rename;
20
19use std::{fmt, sync::Arc}; 21use std::{fmt, sync::Arc};
20 22
21use base_db::{ 23use base_db::{
diff --git a/crates/ide_db/src/rename.rs b/crates/ide_db/src/rename.rs
new file mode 100644
index 000000000..877650df0
--- /dev/null
+++ b/crates/ide_db/src/rename.rs
@@ -0,0 +1,444 @@
1use std::fmt;
2
3use base_db::{AnchoredPathBuf, FileId, FileRange};
4use either::Either;
5use hir::{AsAssocItem, FieldSource, HasSource, InFile, ModuleSource, Semantics};
6use stdx::never;
7use syntax::{
8 ast::{self, NameOwner},
9 lex_single_syntax_kind, AstNode, SyntaxKind, TextRange, T,
10};
11use text_edit::TextEdit;
12
13use crate::{
14 defs::Definition,
15 search::FileReference,
16 source_change::{FileSystemEdit, SourceChange},
17 RootDatabase,
18};
19
20pub type Result<T, E = RenameError> = std::result::Result<T, E>;
21
22#[derive(Debug)]
23pub struct RenameError(pub String);
24
25impl fmt::Display for RenameError {
26 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27 fmt::Display::fmt(&self.0, f)
28 }
29}
30
31#[macro_export]
32macro_rules! _format_err {
33 ($fmt:expr) => { RenameError(format!($fmt)) };
34 ($fmt:expr, $($arg:tt)+) => { RenameError(format!($fmt, $($arg)+)) }
35}
36pub use _format_err as format_err;
37
38#[macro_export]
39macro_rules! _bail {
40 ($($tokens:tt)*) => { return Err(format_err!($($tokens)*)) }
41}
42pub use _bail as bail;
43
44impl Definition {
45 pub fn rename(&self, sema: &Semantics<RootDatabase>, new_name: &str) -> Result<SourceChange> {
46 match *self {
47 Definition::ModuleDef(hir::ModuleDef::Module(module)) => {
48 rename_mod(sema, module, new_name)
49 }
50 Definition::ModuleDef(hir::ModuleDef::BuiltinType(_)) => {
51 bail!("Cannot rename builtin type")
52 }
53 Definition::SelfType(_) => bail!("Cannot rename `Self`"),
54 def => rename_reference(sema, def, new_name),
55 }
56 }
57
58 /// Textual range of the identifier which will change when renaming this
59 /// `Definition`. Note that some definitions, like buitin types, can't be
60 /// renamed.
61 pub fn rename_range(self, sema: &Semantics<RootDatabase>) -> Option<FileRange> {
62 // FIXME: the `original_file_range` calls here are wrong -- they never fail,
63 // and _fall back_ to the entirety of the macro call. Such fall back is
64 // incorrect for renames. The safe behavior would be to return an error for
65 // such cases. The correct behavior would be to return an auxiliary list of
66 // "can't rename these occurrences in macros" items, and then show some kind
67 // of a dialog to the user.
68
69 let res = match self {
70 Definition::Macro(mac) => {
71 let src = mac.source(sema.db)?;
72 let name = match &src.value {
73 Either::Left(it) => it.name()?,
74 Either::Right(it) => it.name()?,
75 };
76 src.with_value(name.syntax()).original_file_range(sema.db)
77 }
78 Definition::Field(field) => {
79 let src = field.source(sema.db)?;
80
81 match &src.value {
82 FieldSource::Named(record_field) => {
83 let name = record_field.name()?;
84 src.with_value(name.syntax()).original_file_range(sema.db)
85 }
86 FieldSource::Pos(_) => {
87 return None;
88 }
89 }
90 }
91 Definition::ModuleDef(module_def) => match module_def {
92 hir::ModuleDef::Module(module) => {
93 let src = module.declaration_source(sema.db)?;
94 let name = src.value.name()?;
95 src.with_value(name.syntax()).original_file_range(sema.db)
96 }
97 hir::ModuleDef::Function(it) => name_range(it, sema)?,
98 hir::ModuleDef::Adt(adt) => match adt {
99 hir::Adt::Struct(it) => name_range(it, sema)?,
100 hir::Adt::Union(it) => name_range(it, sema)?,
101 hir::Adt::Enum(it) => name_range(it, sema)?,
102 },
103 hir::ModuleDef::Variant(it) => name_range(it, sema)?,
104 hir::ModuleDef::Const(it) => name_range(it, sema)?,
105 hir::ModuleDef::Static(it) => name_range(it, sema)?,
106 hir::ModuleDef::Trait(it) => name_range(it, sema)?,
107 hir::ModuleDef::TypeAlias(it) => name_range(it, sema)?,
108 hir::ModuleDef::BuiltinType(_) => return None,
109 },
110 Definition::SelfType(_) => return None,
111 Definition::Local(local) => {
112 let src = local.source(sema.db);
113 let name = match &src.value {
114 Either::Left(bind_pat) => bind_pat.name()?,
115 Either::Right(_) => return None,
116 };
117 src.with_value(name.syntax()).original_file_range(sema.db)
118 }
119 Definition::GenericParam(generic_param) => match generic_param {
120 hir::GenericParam::TypeParam(type_param) => {
121 let src = type_param.source(sema.db)?;
122 let name = match &src.value {
123 Either::Left(_) => return None,
124 Either::Right(type_param) => type_param.name()?,
125 };
126 src.with_value(name.syntax()).original_file_range(sema.db)
127 }
128 hir::GenericParam::LifetimeParam(lifetime_param) => {
129 let src = lifetime_param.source(sema.db)?;
130 let lifetime = src.value.lifetime()?;
131 src.with_value(lifetime.syntax()).original_file_range(sema.db)
132 }
133 hir::GenericParam::ConstParam(it) => name_range(it, sema)?,
134 },
135 Definition::Label(label) => {
136 let src = label.source(sema.db);
137 let lifetime = src.value.lifetime()?;
138 src.with_value(lifetime.syntax()).original_file_range(sema.db)
139 }
140 };
141 return Some(res);
142
143 fn name_range<D>(def: D, sema: &Semantics<RootDatabase>) -> Option<FileRange>
144 where
145 D: HasSource,
146 D::Ast: ast::NameOwner,
147 {
148 let src = def.source(sema.db)?;
149 let name = src.value.name()?;
150 let res = src.with_value(name.syntax()).original_file_range(sema.db);
151 Some(res)
152 }
153 }
154}
155
156fn rename_mod(
157 sema: &Semantics<RootDatabase>,
158 module: hir::Module,
159 new_name: &str,
160) -> Result<SourceChange> {
161 if IdentifierKind::classify(new_name)? != IdentifierKind::Ident {
162 bail!("Invalid name `{0}`: cannot rename module to {0}", new_name);
163 }
164
165 let mut source_change = SourceChange::default();
166
167 let InFile { file_id, value: def_source } = module.definition_source(sema.db);
168 let file_id = file_id.original_file(sema.db);
169 if let ModuleSource::SourceFile(..) = def_source {
170 // mod is defined in path/to/dir/mod.rs
171 let path = if module.is_mod_rs(sema.db) {
172 format!("../{}/mod.rs", new_name)
173 } else {
174 format!("{}.rs", new_name)
175 };
176 let dst = AnchoredPathBuf { anchor: file_id, path };
177 let move_file = FileSystemEdit::MoveFile { src: file_id, dst };
178 source_change.push_file_system_edit(move_file);
179 }
180
181 if let Some(InFile { file_id, value: decl_source }) = module.declaration_source(sema.db) {
182 let file_id = file_id.original_file(sema.db);
183 match decl_source.name() {
184 Some(name) => source_change.insert_source_edit(
185 file_id,
186 TextEdit::replace(name.syntax().text_range(), new_name.to_string()),
187 ),
188 _ => never!("Module source node is missing a name"),
189 }
190 }
191 let def = Definition::ModuleDef(hir::ModuleDef::Module(module));
192 let usages = def.usages(sema).all();
193 let ref_edits = usages.iter().map(|(&file_id, references)| {
194 (file_id, source_edit_from_references(references, def, new_name))
195 });
196 source_change.extend(ref_edits);
197
198 Ok(source_change)
199}
200
201fn rename_reference(
202 sema: &Semantics<RootDatabase>,
203 mut def: Definition,
204 new_name: &str,
205) -> Result<SourceChange> {
206 let ident_kind = IdentifierKind::classify(new_name)?;
207
208 if matches!(
209 def, // is target a lifetime?
210 Definition::GenericParam(hir::GenericParam::LifetimeParam(_)) | Definition::Label(_)
211 ) {
212 match ident_kind {
213 IdentifierKind::Ident | IdentifierKind::Underscore => {
214 cov_mark::hit!(rename_not_a_lifetime_ident_ref);
215 bail!("Invalid name `{}`: not a lifetime identifier", new_name);
216 }
217 IdentifierKind::Lifetime => cov_mark::hit!(rename_lifetime),
218 }
219 } else {
220 match (ident_kind, def) {
221 (IdentifierKind::Lifetime, _) => {
222 cov_mark::hit!(rename_not_an_ident_ref);
223 bail!("Invalid name `{}`: not an identifier", new_name);
224 }
225 (IdentifierKind::Ident, _) => cov_mark::hit!(rename_non_local),
226 (IdentifierKind::Underscore, _) => (),
227 }
228 }
229
230 def = match def {
231 // HACK: resolve trait impl items to the item def of the trait definition
232 // so that we properly resolve all trait item references
233 Definition::ModuleDef(mod_def) => mod_def
234 .as_assoc_item(sema.db)
235 .and_then(|it| it.containing_trait_impl(sema.db))
236 .and_then(|it| {
237 it.items(sema.db).into_iter().find_map(|it| match (it, mod_def) {
238 (hir::AssocItem::Function(trait_func), hir::ModuleDef::Function(func))
239 if trait_func.name(sema.db) == func.name(sema.db) =>
240 {
241 Some(Definition::ModuleDef(hir::ModuleDef::Function(trait_func)))
242 }
243 (hir::AssocItem::Const(trait_konst), hir::ModuleDef::Const(konst))
244 if trait_konst.name(sema.db) == konst.name(sema.db) =>
245 {
246 Some(Definition::ModuleDef(hir::ModuleDef::Const(trait_konst)))
247 }
248 (
249 hir::AssocItem::TypeAlias(trait_type_alias),
250 hir::ModuleDef::TypeAlias(type_alias),
251 ) if trait_type_alias.name(sema.db) == type_alias.name(sema.db) => {
252 Some(Definition::ModuleDef(hir::ModuleDef::TypeAlias(trait_type_alias)))
253 }
254 _ => None,
255 })
256 })
257 .unwrap_or(def),
258 _ => def,
259 };
260 let usages = def.usages(sema).all();
261
262 if !usages.is_empty() && ident_kind == IdentifierKind::Underscore {
263 cov_mark::hit!(rename_underscore_multiple);
264 bail!("Cannot rename reference to `_` as it is being referenced multiple times");
265 }
266 let mut source_change = SourceChange::default();
267 source_change.extend(usages.iter().map(|(&file_id, references)| {
268 (file_id, source_edit_from_references(references, def, new_name))
269 }));
270
271 let (file_id, edit) = source_edit_from_def(sema, def, new_name)?;
272 source_change.insert_source_edit(file_id, edit);
273 Ok(source_change)
274}
275
276pub fn source_edit_from_references(
277 references: &[FileReference],
278 def: Definition,
279 new_name: &str,
280) -> TextEdit {
281 let mut edit = TextEdit::builder();
282 for reference in references {
283 let (range, replacement) = match &reference.name {
284 // if the ranges differ then the node is inside a macro call, we can't really attempt
285 // to make special rewrites like shorthand syntax and such, so just rename the node in
286 // the macro input
287 ast::NameLike::NameRef(name_ref)
288 if name_ref.syntax().text_range() == reference.range =>
289 {
290 source_edit_from_name_ref(name_ref, new_name, def)
291 }
292 ast::NameLike::Name(name) if name.syntax().text_range() == reference.range => {
293 source_edit_from_name(name, new_name)
294 }
295 _ => None,
296 }
297 .unwrap_or_else(|| (reference.range, new_name.to_string()));
298 edit.replace(range, replacement);
299 }
300 edit.finish()
301}
302
303fn source_edit_from_name(name: &ast::Name, new_name: &str) -> Option<(TextRange, String)> {
304 if let Some(_) = ast::RecordPatField::for_field_name(name) {
305 if let Some(ident_pat) = name.syntax().parent().and_then(ast::IdentPat::cast) {
306 return Some((
307 TextRange::empty(ident_pat.syntax().text_range().start()),
308 [new_name, ": "].concat(),
309 ));
310 }
311 }
312 None
313}
314
315fn source_edit_from_name_ref(
316 name_ref: &ast::NameRef,
317 new_name: &str,
318 def: Definition,
319) -> Option<(TextRange, String)> {
320 if let Some(record_field) = ast::RecordExprField::for_name_ref(name_ref) {
321 let rcf_name_ref = record_field.name_ref();
322 let rcf_expr = record_field.expr();
323 match (rcf_name_ref, rcf_expr.and_then(|it| it.name_ref())) {
324 // field: init-expr, check if we can use a field init shorthand
325 (Some(field_name), Some(init)) => {
326 if field_name == *name_ref {
327 if init.text() == new_name {
328 cov_mark::hit!(test_rename_field_put_init_shorthand);
329 // same names, we can use a shorthand here instead.
330 // we do not want to erase attributes hence this range start
331 let s = field_name.syntax().text_range().start();
332 let e = record_field.syntax().text_range().end();
333 return Some((TextRange::new(s, e), new_name.to_owned()));
334 }
335 } else if init == *name_ref {
336 if field_name.text() == new_name {
337 cov_mark::hit!(test_rename_local_put_init_shorthand);
338 // same names, we can use a shorthand here instead.
339 // we do not want to erase attributes hence this range start
340 let s = field_name.syntax().text_range().start();
341 let e = record_field.syntax().text_range().end();
342 return Some((TextRange::new(s, e), new_name.to_owned()));
343 }
344 }
345 None
346 }
347 // init shorthand
348 // FIXME: instead of splitting the shorthand, recursively trigger a rename of the
349 // other name https://github.com/rust-analyzer/rust-analyzer/issues/6547
350 (None, Some(_)) if matches!(def, Definition::Field(_)) => {
351 cov_mark::hit!(test_rename_field_in_field_shorthand);
352 let s = name_ref.syntax().text_range().start();
353 Some((TextRange::empty(s), format!("{}: ", new_name)))
354 }
355 (None, Some(_)) if matches!(def, Definition::Local(_)) => {
356 cov_mark::hit!(test_rename_local_in_field_shorthand);
357 let s = name_ref.syntax().text_range().end();
358 Some((TextRange::empty(s), format!(": {}", new_name)))
359 }
360 _ => None,
361 }
362 } else if let Some(record_field) = ast::RecordPatField::for_field_name_ref(name_ref) {
363 let rcf_name_ref = record_field.name_ref();
364 let rcf_pat = record_field.pat();
365 match (rcf_name_ref, rcf_pat) {
366 // field: rename
367 (Some(field_name), Some(ast::Pat::IdentPat(pat))) if field_name == *name_ref => {
368 // field name is being renamed
369 if pat.name().map_or(false, |it| it.text() == new_name) {
370 cov_mark::hit!(test_rename_field_put_init_shorthand_pat);
371 // same names, we can use a shorthand here instead/
372 // we do not want to erase attributes hence this range start
373 let s = field_name.syntax().text_range().start();
374 let e = record_field.syntax().text_range().end();
375 Some((TextRange::new(s, e), pat.to_string()))
376 } else {
377 None
378 }
379 }
380 _ => None,
381 }
382 } else {
383 None
384 }
385}
386
387fn source_edit_from_def(
388 sema: &Semantics<RootDatabase>,
389 def: Definition,
390 new_name: &str,
391) -> Result<(FileId, TextEdit)> {
392 let frange =
393 def.rename_range(sema).ok_or_else(|| format_err!("No identifier available to rename"))?;
394
395 let mut replacement_text = String::new();
396 let mut repl_range = frange.range;
397 if let Definition::Local(local) = def {
398 if let Either::Left(pat) = local.source(sema.db).value {
399 if matches!(
400 pat.syntax().parent().and_then(ast::RecordPatField::cast),
401 Some(pat_field) if pat_field.name_ref().is_none()
402 ) {
403 replacement_text.push_str(": ");
404 replacement_text.push_str(new_name);
405 repl_range = TextRange::new(
406 pat.syntax().text_range().end(),
407 pat.syntax().text_range().end(),
408 );
409 }
410 }
411 }
412 if replacement_text.is_empty() {
413 replacement_text.push_str(new_name);
414 }
415 let edit = TextEdit::replace(repl_range, replacement_text);
416 Ok((frange.file_id, edit))
417}
418
419#[derive(Copy, Clone, Debug, PartialEq)]
420pub enum IdentifierKind {
421 Ident,
422 Lifetime,
423 Underscore,
424}
425
426impl IdentifierKind {
427 pub fn classify(new_name: &str) -> Result<IdentifierKind> {
428 match lex_single_syntax_kind(new_name) {
429 Some(res) => match res {
430 (SyntaxKind::IDENT, _) => Ok(IdentifierKind::Ident),
431 (T![_], _) => Ok(IdentifierKind::Underscore),
432 (SyntaxKind::LIFETIME_IDENT, _) if new_name != "'static" && new_name != "'_" => {
433 Ok(IdentifierKind::Lifetime)
434 }
435 (SyntaxKind::LIFETIME_IDENT, _) => {
436 bail!("Invalid name `{}`: not a lifetime identifier", new_name)
437 }
438 (_, Some(syntax_error)) => bail!("Invalid name `{}`: {}", new_name, syntax_error),
439 (_, None) => bail!("Invalid name `{}`: not an identifier", new_name),
440 },
441 None => bail!("Invalid name `{}`: not an identifier", new_name),
442 }
443 }
444}
diff --git a/crates/ide_diagnostics/src/incorrect_case.rs b/crates/ide_diagnostics/src/incorrect_case.rs
index 8e1a93aa7..2cf232d56 100644
--- a/crates/ide_diagnostics/src/incorrect_case.rs
+++ b/crates/ide_diagnostics/src/incorrect_case.rs
@@ -1,5 +1,5 @@
1use hir::{db::AstDatabase, InFile}; 1use hir::{db::AstDatabase, InFile};
2use ide_db::{assists::Assist, base_db::FilePosition}; 2use ide_db::{assists::Assist, defs::NameClass};
3use syntax::AstNode; 3use syntax::AstNode;
4 4
5use crate::{ 5use crate::{
@@ -27,35 +27,26 @@ pub(super) fn incorrect_case(ctx: &DiagnosticsContext<'_>, d: &hir::IncorrectCas
27} 27}
28 28
29fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::IncorrectCase) -> Option<Vec<Assist>> { 29fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::IncorrectCase) -> Option<Vec<Assist>> {
30 if true {
31 return None;
32 }
33
34 let root = ctx.sema.db.parse_or_expand(d.file)?; 30 let root = ctx.sema.db.parse_or_expand(d.file)?;
35 let name_node = d.ident.to_node(&root); 31 let name_node = d.ident.to_node(&root);
32 let def = NameClass::classify(&ctx.sema, &name_node)?.defined(ctx.sema.db)?;
36 33
37 let name_node = InFile::new(d.file, name_node.syntax()); 34 let name_node = InFile::new(d.file, name_node.syntax());
38 let frange = name_node.original_file_range(ctx.sema.db); 35 let frange = name_node.original_file_range(ctx.sema.db);
39 let _file_position = FilePosition { file_id: frange.file_id, offset: frange.range.start() };
40 36
41 let label = format!("Rename to {}", d.suggested_text); 37 let label = format!("Rename to {}", d.suggested_text);
42 let res = unresolved_fix("change_case", &label, frange.range); 38 let mut res = unresolved_fix("change_case", &label, frange.range);
43 if ctx.resolve.should_resolve(&res.id) { 39 if ctx.resolve.should_resolve(&res.id) {
44 //let source_change = rename_with_semantics(&ctx.sema, file_position, &d.suggested_text); 40 let source_change = def.rename(&ctx.sema, &d.suggested_text);
45 //res.source_change = Some(source_change.ok().unwrap_or_default()); 41 res.source_change = Some(source_change.ok().unwrap_or_default());
46 todo!()
47 } 42 }
48 43
49 Some(vec![res]) 44 Some(vec![res])
50} 45}
51 46
52#[cfg(TODO)] 47#[cfg(test)]
53mod change_case { 48mod change_case {
54 use crate::{ 49 use crate::tests::{check_diagnostics, check_fix};
55 fixture,
56 tests::{check_diagnostics, check_fix},
57 AssistResolveStrategy, DiagnosticsConfig,
58 };
59 50
60 #[test] 51 #[test]
61 fn test_rename_incorrect_case() { 52 fn test_rename_incorrect_case() {
@@ -123,7 +114,7 @@ fn some_fn() {
123 check_diagnostics( 114 check_diagnostics(
124 r#" 115 r#"
125fn foo() { 116fn foo() {
126 const ANOTHER_ITEM$0: &str = "some_item"; 117 const ANOTHER_ITEM: &str = "some_item";
127} 118}
128"#, 119"#,
129 ); 120 );
@@ -155,20 +146,13 @@ impl TestStruct {
155 146
156 #[test] 147 #[test]
157 fn test_single_incorrect_case_diagnostic_in_function_name_issue_6970() { 148 fn test_single_incorrect_case_diagnostic_in_function_name_issue_6970() {
158 let input = r#"fn FOO$0() {}"#; 149 check_diagnostics(
159 let expected = r#"fn foo() {}"#; 150 r#"
160 151fn FOO() {}
161 let (analysis, file_position) = fixture::position(input); 152// ^^^ Function `FOO` should have snake_case name, e.g. `foo`
162 let diagnostics = analysis 153"#,
163 .diagnostics( 154 );
164 &DiagnosticsConfig::default(), 155 check_fix(r#"fn FOO$0() {}"#, r#"fn foo() {}"#);
165 AssistResolveStrategy::All,
166 file_position.file_id,
167 )
168 .unwrap();
169 assert_eq!(diagnostics.len(), 1);
170
171 check_fix(input, expected);
172 } 156 }
173 157
174 #[test] 158 #[test]