mirror of
https://github.com/rust-lang/rust-analyzer
synced 2025-01-14 14:13:58 +00:00
Auto merge of #16391 - alibektas:15656/renaming_allowed_by_config, r=Veykril
Add a new config to allow renaming of non-local defs With #15656 we started disallowing renaming of non-local items. Although this makes sense there are some false positives that impacted users' workflows. So this config aims to mitigate this by giving users the liberty to disable this feature. The reason why this is a draft is that I saw one of the tests fail and I am not sure if the "got" result even syntactically makes sense Test case is : ```rust check( "Baz", r#" //- /lib.rs crate:lib new_source_root:library pub struct S; //- /main.rs crate:main deps:lib new_source_root:local use lib::S$0; "#, "use lib::Baz;" ); ``` ``` Left: use lib::Baz; Right: use lib::Baz;Baz Diff: use lib::Baz;Baz ```
This commit is contained in:
commit
a5b89fffb6
8 changed files with 77 additions and 29 deletions
|
@ -71,14 +71,17 @@ impl Definition {
|
||||||
&self,
|
&self,
|
||||||
sema: &Semantics<'_, RootDatabase>,
|
sema: &Semantics<'_, RootDatabase>,
|
||||||
new_name: &str,
|
new_name: &str,
|
||||||
|
rename_external: bool,
|
||||||
) -> Result<SourceChange> {
|
) -> Result<SourceChange> {
|
||||||
// self.krate() returns None if
|
// self.krate() returns None if
|
||||||
// self is a built-in attr, built-in type or tool module.
|
// self is a built-in attr, built-in type or tool module.
|
||||||
// it is not allowed for these defs to be renamed.
|
// it is not allowed for these defs to be renamed.
|
||||||
// cases where self.krate() is None is handled below.
|
// cases where self.krate() is None is handled below.
|
||||||
if let Some(krate) = self.krate(sema.db) {
|
if let Some(krate) = self.krate(sema.db) {
|
||||||
if !krate.origin(sema.db).is_local() {
|
// Can we not rename non-local items?
|
||||||
bail!("Cannot rename a non-local definition.")
|
// Then bail if non-local
|
||||||
|
if !rename_external && !krate.origin(sema.db).is_local() {
|
||||||
|
bail!("Cannot rename a non-local definition. Set `renameExternalItems` to `true` to allow renaming for this item.")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -43,7 +43,7 @@ fn fixes(ctx: &DiagnosticsContext<'_>, d: &hir::IncorrectCase) -> Option<Vec<Ass
|
||||||
let label = format!("Rename to {}", d.suggested_text);
|
let label = format!("Rename to {}", d.suggested_text);
|
||||||
let mut res = unresolved_fix("change_case", &label, frange.range);
|
let mut res = unresolved_fix("change_case", &label, frange.range);
|
||||||
if ctx.resolve.should_resolve(&res.id) {
|
if ctx.resolve.should_resolve(&res.id) {
|
||||||
let source_change = def.rename(&ctx.sema, &d.suggested_text);
|
let source_change = def.rename(&ctx.sema, &d.suggested_text, true);
|
||||||
res.source_change = Some(source_change.ok().unwrap_or_default());
|
res.source_change = Some(source_change.ok().unwrap_or_default());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -680,8 +680,9 @@ impl Analysis {
|
||||||
&self,
|
&self,
|
||||||
position: FilePosition,
|
position: FilePosition,
|
||||||
new_name: &str,
|
new_name: &str,
|
||||||
|
rename_external: bool,
|
||||||
) -> Cancellable<Result<SourceChange, RenameError>> {
|
) -> Cancellable<Result<SourceChange, RenameError>> {
|
||||||
self.with_db(|db| rename::rename(db, position, new_name))
|
self.with_db(|db| rename::rename(db, position, new_name, rename_external))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn prepare_rename(
|
pub fn prepare_rename(
|
||||||
|
|
|
@ -84,6 +84,7 @@ pub(crate) fn rename(
|
||||||
db: &RootDatabase,
|
db: &RootDatabase,
|
||||||
position: FilePosition,
|
position: FilePosition,
|
||||||
new_name: &str,
|
new_name: &str,
|
||||||
|
rename_external: bool,
|
||||||
) -> RenameResult<SourceChange> {
|
) -> RenameResult<SourceChange> {
|
||||||
let sema = Semantics::new(db);
|
let sema = Semantics::new(db);
|
||||||
let source_file = sema.parse(position.file_id);
|
let source_file = sema.parse(position.file_id);
|
||||||
|
@ -103,7 +104,7 @@ pub(crate) fn rename(
|
||||||
return rename_to_self(&sema, local);
|
return rename_to_self(&sema, local);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
def.rename(&sema, new_name)
|
def.rename(&sema, new_name, rename_external)
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
|
@ -122,9 +123,9 @@ pub(crate) fn will_rename_file(
|
||||||
let module = sema.to_module_def(file_id)?;
|
let module = sema.to_module_def(file_id)?;
|
||||||
let def = Definition::Module(module);
|
let def = Definition::Module(module);
|
||||||
let mut change = if is_raw_identifier(new_name_stem) {
|
let mut change = if is_raw_identifier(new_name_stem) {
|
||||||
def.rename(&sema, &SmolStr::from_iter(["r#", new_name_stem])).ok()?
|
def.rename(&sema, &SmolStr::from_iter(["r#", new_name_stem]), true).ok()?
|
||||||
} else {
|
} else {
|
||||||
def.rename(&sema, new_name_stem).ok()?
|
def.rename(&sema, new_name_stem, true).ok()?
|
||||||
};
|
};
|
||||||
change.file_system_edits.clear();
|
change.file_system_edits.clear();
|
||||||
Some(change)
|
Some(change)
|
||||||
|
@ -371,12 +372,21 @@ mod tests {
|
||||||
use test_utils::assert_eq_text;
|
use test_utils::assert_eq_text;
|
||||||
use text_edit::TextEdit;
|
use text_edit::TextEdit;
|
||||||
|
|
||||||
use crate::{fixture, FileId};
|
use crate::fixture;
|
||||||
|
|
||||||
use super::{RangeInfo, RenameError};
|
use super::{RangeInfo, RenameError};
|
||||||
|
|
||||||
#[track_caller]
|
|
||||||
fn check(new_name: &str, ra_fixture_before: &str, ra_fixture_after: &str) {
|
fn check(new_name: &str, ra_fixture_before: &str, ra_fixture_after: &str) {
|
||||||
|
check_with_rename_config(new_name, ra_fixture_before, ra_fixture_after, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[track_caller]
|
||||||
|
fn check_with_rename_config(
|
||||||
|
new_name: &str,
|
||||||
|
ra_fixture_before: &str,
|
||||||
|
ra_fixture_after: &str,
|
||||||
|
rename_external: bool,
|
||||||
|
) {
|
||||||
let ra_fixture_after = &trim_indent(ra_fixture_after);
|
let ra_fixture_after = &trim_indent(ra_fixture_after);
|
||||||
let (analysis, position) = fixture::position(ra_fixture_before);
|
let (analysis, position) = fixture::position(ra_fixture_before);
|
||||||
if !ra_fixture_after.starts_with("error: ") {
|
if !ra_fixture_after.starts_with("error: ") {
|
||||||
|
@ -385,23 +395,22 @@ mod tests {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let rename_result = analysis
|
let rename_result = analysis
|
||||||
.rename(position, new_name)
|
.rename(position, new_name, rename_external)
|
||||||
.unwrap_or_else(|err| panic!("Rename to '{new_name}' was cancelled: {err}"));
|
.unwrap_or_else(|err| panic!("Rename to '{new_name}' was cancelled: {err}"));
|
||||||
match rename_result {
|
match rename_result {
|
||||||
Ok(source_change) => {
|
Ok(source_change) => {
|
||||||
let mut text_edit_builder = TextEdit::builder();
|
let mut text_edit_builder = TextEdit::builder();
|
||||||
let mut file_id: Option<FileId> = None;
|
let (&file_id, edit) = match source_change.source_file_edits.len() {
|
||||||
for edit in source_change.source_file_edits {
|
0 => return,
|
||||||
file_id = Some(edit.0);
|
1 => source_change.source_file_edits.iter().next().unwrap(),
|
||||||
for indel in edit.1 .0.into_iter() {
|
_ => (&position.file_id, &source_change.source_file_edits[&position.file_id]),
|
||||||
text_edit_builder.replace(indel.delete, indel.insert);
|
};
|
||||||
}
|
for indel in edit.0.iter() {
|
||||||
}
|
text_edit_builder.replace(indel.delete, indel.insert.clone());
|
||||||
if let Some(file_id) = file_id {
|
|
||||||
let mut result = analysis.file_text(file_id).unwrap().to_string();
|
|
||||||
text_edit_builder.finish().apply(&mut result);
|
|
||||||
assert_eq_text!(ra_fixture_after, &*result);
|
|
||||||
}
|
}
|
||||||
|
let mut result = analysis.file_text(file_id).unwrap().to_string();
|
||||||
|
text_edit_builder.finish().apply(&mut result);
|
||||||
|
assert_eq_text!(ra_fixture_after, &*result);
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
if ra_fixture_after.starts_with("error:") {
|
if ra_fixture_after.starts_with("error:") {
|
||||||
|
@ -417,8 +426,10 @@ mod tests {
|
||||||
|
|
||||||
fn check_expect(new_name: &str, ra_fixture: &str, expect: Expect) {
|
fn check_expect(new_name: &str, ra_fixture: &str, expect: Expect) {
|
||||||
let (analysis, position) = fixture::position(ra_fixture);
|
let (analysis, position) = fixture::position(ra_fixture);
|
||||||
let source_change =
|
let source_change = analysis
|
||||||
analysis.rename(position, new_name).unwrap().expect("Expect returned a RenameError");
|
.rename(position, new_name, true)
|
||||||
|
.unwrap()
|
||||||
|
.expect("Expect returned a RenameError");
|
||||||
expect.assert_eq(&filter_expect(source_change))
|
expect.assert_eq(&filter_expect(source_change))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -2617,6 +2628,18 @@ use qux as frob;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn disallow_renaming_for_non_local_definition() {
|
fn disallow_renaming_for_non_local_definition() {
|
||||||
|
check_with_rename_config(
|
||||||
|
"Baz",
|
||||||
|
r#"
|
||||||
|
//- /lib.rs crate:lib new_source_root:library
|
||||||
|
pub struct S;
|
||||||
|
//- /main.rs crate:main deps:lib new_source_root:local
|
||||||
|
use lib::S$0;
|
||||||
|
"#,
|
||||||
|
"error: Cannot rename a non-local definition. Set `renameExternalItems` to `true` to allow renaming for this item.",
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
|
||||||
check(
|
check(
|
||||||
"Baz",
|
"Baz",
|
||||||
r#"
|
r#"
|
||||||
|
@ -2625,13 +2648,13 @@ pub struct S;
|
||||||
//- /main.rs crate:main deps:lib new_source_root:local
|
//- /main.rs crate:main deps:lib new_source_root:local
|
||||||
use lib::S$0;
|
use lib::S$0;
|
||||||
"#,
|
"#,
|
||||||
"error: Cannot rename a non-local definition.",
|
"use lib::Baz;\n",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn disallow_renaming_for_builtin_macros() {
|
fn disallow_renaming_for_builtin_macros() {
|
||||||
check(
|
check_with_rename_config(
|
||||||
"Baz",
|
"Baz",
|
||||||
r#"
|
r#"
|
||||||
//- minicore: derive, hash
|
//- minicore: derive, hash
|
||||||
|
@ -2640,8 +2663,9 @@ use core::hash::Hash;
|
||||||
#[derive(H$0ash)]
|
#[derive(H$0ash)]
|
||||||
struct A;
|
struct A;
|
||||||
"#,
|
"#,
|
||||||
"error: Cannot rename a non-local definition.",
|
"error: Cannot rename a non-local definition. Set `renameExternalItems` to `true` to allow renaming for this item.",
|
||||||
)
|
false,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
|
@ -494,6 +494,10 @@ config_data! {
|
||||||
/// Exclude imports from find-all-references.
|
/// Exclude imports from find-all-references.
|
||||||
references_excludeImports: bool = "false",
|
references_excludeImports: bool = "false",
|
||||||
|
|
||||||
|
/// Allow renaming of items not belonging to the loaded workspaces.
|
||||||
|
rename_allowExternalItems: bool = "false",
|
||||||
|
|
||||||
|
|
||||||
/// Command to be executed instead of 'cargo' for runnables.
|
/// Command to be executed instead of 'cargo' for runnables.
|
||||||
runnables_command: Option<String> = "null",
|
runnables_command: Option<String> = "null",
|
||||||
/// Additional arguments to be passed to cargo for runnables such as
|
/// Additional arguments to be passed to cargo for runnables such as
|
||||||
|
@ -1739,6 +1743,10 @@ impl Config {
|
||||||
self.data.typing_autoClosingAngleBrackets_enable
|
self.data.typing_autoClosingAngleBrackets_enable
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn rename(&self) -> bool {
|
||||||
|
self.data.rename_allowExternalItems
|
||||||
|
}
|
||||||
|
|
||||||
// FIXME: VSCode seems to work wrong sometimes, see https://github.com/microsoft/vscode/issues/193124
|
// FIXME: VSCode seems to work wrong sometimes, see https://github.com/microsoft/vscode/issues/193124
|
||||||
// hence, distinguish it for now.
|
// hence, distinguish it for now.
|
||||||
pub fn is_visual_studio_code(&self) -> bool {
|
pub fn is_visual_studio_code(&self) -> bool {
|
||||||
|
|
|
@ -1017,8 +1017,10 @@ pub(crate) fn handle_rename(
|
||||||
let _p = profile::span("handle_rename");
|
let _p = profile::span("handle_rename");
|
||||||
let position = from_proto::file_position(&snap, params.text_document_position)?;
|
let position = from_proto::file_position(&snap, params.text_document_position)?;
|
||||||
|
|
||||||
let mut change =
|
let mut change = snap
|
||||||
snap.analysis.rename(position, ¶ms.new_name)?.map_err(to_proto::rename_error)?;
|
.analysis
|
||||||
|
.rename(position, ¶ms.new_name, snap.config.rename())?
|
||||||
|
.map_err(to_proto::rename_error)?;
|
||||||
|
|
||||||
// this is kind of a hack to prevent double edits from happening when moving files
|
// this is kind of a hack to prevent double edits from happening when moving files
|
||||||
// When a module gets renamed by renaming the mod declaration this causes the file to move
|
// When a module gets renamed by renaming the mod declaration this causes the file to move
|
||||||
|
|
|
@ -777,6 +777,11 @@ Internal config, path to proc-macro server executable.
|
||||||
--
|
--
|
||||||
Exclude imports from find-all-references.
|
Exclude imports from find-all-references.
|
||||||
--
|
--
|
||||||
|
[[rust-analyzer.rename.allowExternalItems]]rust-analyzer.rename.allowExternalItems (default: `false`)::
|
||||||
|
+
|
||||||
|
--
|
||||||
|
Allow renaming of items not belonging to the loaded workspaces.
|
||||||
|
--
|
||||||
[[rust-analyzer.runnables.command]]rust-analyzer.runnables.command (default: `null`)::
|
[[rust-analyzer.runnables.command]]rust-analyzer.runnables.command (default: `null`)::
|
||||||
+
|
+
|
||||||
--
|
--
|
||||||
|
|
|
@ -1503,6 +1503,11 @@
|
||||||
"default": false,
|
"default": false,
|
||||||
"type": "boolean"
|
"type": "boolean"
|
||||||
},
|
},
|
||||||
|
"rust-analyzer.rename.allowExternalItems": {
|
||||||
|
"markdownDescription": "Allow renaming of items not belonging to the loaded workspaces.",
|
||||||
|
"default": false,
|
||||||
|
"type": "boolean"
|
||||||
|
},
|
||||||
"rust-analyzer.runnables.command": {
|
"rust-analyzer.runnables.command": {
|
||||||
"markdownDescription": "Command to be executed instead of 'cargo' for runnables.",
|
"markdownDescription": "Command to be executed instead of 'cargo' for runnables.",
|
||||||
"default": null,
|
"default": null,
|
||||||
|
|
Loading…
Reference in a new issue