Skip to content

Commit c1f0e60

Browse files
committed
fix: handle empty /**/ in block_to_line assist
block_to_line sliced &text[prefix.len()..text.len()-2], which panicked on `/**/` since its prefix matches the entire comment (len 4) and text.len() - 2 = 2, producing the invalid range [4..2]. use strip_prefix/strip_suffix and emit a plain `//` when the body is empty after trimming. fixes #22071
1 parent 26d7ba3 commit c1f0e60

1 file changed

Lines changed: 37 additions & 15 deletions

File tree

crates/ide-assists/src/handlers/convert_comment_block.rs

Lines changed: 37 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -46,23 +46,26 @@ fn block_to_line(acc: &mut Assists, comment: ast::Comment) -> Option<()> {
4646
let line_prefix = CommentKind { shape: CommentShape::Line, ..comment.kind() }.prefix();
4747

4848
let text = comment.text();
49-
let text = &text[comment.prefix().len()..(text.len() - "*/".len())].trim();
50-
51-
let lines = text.lines().peekable();
49+
let text = text.strip_prefix(comment.prefix()).unwrap_or(text);
50+
let text = text.strip_suffix("*/").unwrap_or(text).trim();
5251

5352
let indent_spaces = indentation.to_string();
54-
let output = lines
55-
.map(|line| {
56-
let line = line.trim_start_matches(&indent_spaces);
57-
58-
// Don't introduce trailing whitespace
59-
if line.is_empty() {
60-
line_prefix.to_owned()
61-
} else {
62-
format!("{line_prefix} {line}")
63-
}
64-
})
65-
.join(&format!("\n{indent_spaces}"));
53+
let output = if text.is_empty() {
54+
line_prefix.to_owned()
55+
} else {
56+
text.lines()
57+
.map(|line| {
58+
let line = line.trim_start_matches(&indent_spaces);
59+
60+
// Don't introduce trailing whitespace
61+
if line.is_empty() {
62+
line_prefix.to_owned()
63+
} else {
64+
format!("{line_prefix} {line}")
65+
}
66+
})
67+
.join(&format!("\n{indent_spaces}"))
68+
};
6669

6770
edit.replace(target, output)
6871
},
@@ -381,6 +384,25 @@ fn main() {
381384
);
382385
}
383386

387+
#[test]
388+
fn empty_block_to_line() {
389+
check_assist(
390+
convert_comment_block,
391+
r#"
392+
fn main() {
393+
/**/$0
394+
foo();
395+
}
396+
"#,
397+
r#"
398+
fn main() {
399+
//
400+
foo();
401+
}
402+
"#,
403+
);
404+
}
405+
384406
#[test]
385407
fn end_of_line_block_to_line() {
386408
check_assist_not_applicable(

0 commit comments

Comments
 (0)