Skip to content

Commit 7cecd0f

Browse files
bors[bot]detrumi
andauthored
Merge #2449
2449: Only allow renames to valid identifiers r=matklad a=detrumi Implements #2121 Co-authored-by: Wilco Kusee <wilcokusee@gmail.com>
2 parents 10c8e5e + b385656 commit 7cecd0f

File tree

2 files changed

+51
-3
lines changed

2 files changed

+51
-3
lines changed

crates/ra_ide/src/references/rename.rs

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
33
use hir::ModuleSource;
44
use ra_db::{RelativePath, RelativePathBuf, SourceDatabase, SourceDatabaseExt};
5-
use ra_syntax::{algo::find_node_at_offset, ast, AstNode, SyntaxNode};
5+
use ra_syntax::{algo::find_node_at_offset, ast, tokenize, AstNode, SyntaxKind, SyntaxNode};
66
use ra_text_edit::TextEdit;
77

88
use crate::{
@@ -17,6 +17,13 @@ pub(crate) fn rename(
1717
position: FilePosition,
1818
new_name: &str,
1919
) -> Option<RangeInfo<SourceChange>> {
20+
let tokens = tokenize(new_name);
21+
if tokens.len() != 1
22+
|| (tokens[0].kind != SyntaxKind::IDENT && tokens[0].kind != SyntaxKind::UNDERSCORE)
23+
{
24+
return None;
25+
}
26+
2027
let parse = db.parse(position.file_id);
2128
if let Some((ast_name, ast_module)) =
2229
find_name_and_module_at_offset(parse.tree().syntax(), position)
@@ -123,6 +130,49 @@ mod tests {
123130
mock_analysis::analysis_and_position, mock_analysis::single_file_with_position, FileId,
124131
};
125132

133+
#[test]
134+
fn test_rename_to_underscore() {
135+
test_rename(
136+
r#"
137+
fn main() {
138+
let i<|> = 1;
139+
}"#,
140+
"_",
141+
r#"
142+
fn main() {
143+
let _ = 1;
144+
}"#,
145+
);
146+
}
147+
148+
#[test]
149+
fn test_rename_to_raw_identifier() {
150+
test_rename(
151+
r#"
152+
fn main() {
153+
let i<|> = 1;
154+
}"#,
155+
"r#fn",
156+
r#"
157+
fn main() {
158+
let r#fn = 1;
159+
}"#,
160+
);
161+
}
162+
163+
#[test]
164+
fn test_rename_to_invalid_identifier() {
165+
let (analysis, position) = single_file_with_position(
166+
"
167+
fn main() {
168+
let i<|> = 1;
169+
}",
170+
);
171+
let new_name = "invalid!";
172+
let source_change = analysis.rename(position, new_name).unwrap();
173+
assert!(source_change.is_none());
174+
}
175+
126176
#[test]
127177
fn test_rename_for_local() {
128178
test_rename(

crates/ra_lsp_server/src/main_loop/handlers.rs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -480,8 +480,6 @@ pub fn handle_prepare_rename(
480480
let _p = profile("handle_prepare_rename");
481481
let position = params.try_conv_with(&world)?;
482482

483-
// We support renaming references like handle_rename does.
484-
// In the future we may want to reject the renaming of things like keywords here too.
485483
let optional_change = world.analysis().rename(position, "dummy")?;
486484
let range = match optional_change {
487485
None => return Ok(None),

0 commit comments

Comments
 (0)