Skip to content

Commit b240b41

Browse files
committed
feat: add assist to convert char literal
1 parent b31bdc1 commit b240b41

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
use syntax::{AstToken, ast};
2+
3+
use crate::{AssistContext, AssistId, Assists, GroupLabel};
4+
5+
// Assist: convert_char_literal
6+
//
7+
// Converts character literals between different representations. Currently supports normal character -> ASCII / Unicode escape.
8+
pub(crate) fn convert_char_literal(acc: &mut Assists, ctx: &AssistContext<'_>) -> Option<()> {
9+
if !ctx.has_empty_selection() {
10+
return None;
11+
}
12+
13+
let literal = ctx.find_node_at_offset::<ast::Literal>()?;
14+
let literal = match literal.kind() {
15+
ast::LiteralKind::Char(it) => it,
16+
_ => return None,
17+
};
18+
19+
let value = literal.value().ok()?;
20+
let text = literal.syntax().text().to_string();
21+
let range = literal.syntax().text_range();
22+
let group_id = GroupLabel("Convert char representation".into());
23+
24+
let mut add_assist = |converted: String| {
25+
// Skip no-op assists (e.g. `'const C: char = '\\x61';'` already matches the ASCII form).
26+
if converted == text {
27+
return;
28+
}
29+
let label = format!("Convert {text} to {converted}");
30+
acc.add_group(
31+
&group_id,
32+
AssistId::refactor_rewrite("convert_char_literal"),
33+
label,
34+
range,
35+
|builder| builder.replace(range, converted),
36+
);
37+
};
38+
39+
if value.is_ascii() {
40+
add_assist(format!("'\\x{:02x}'", value as u32));
41+
}
42+
43+
add_assist(format!("'\\u{{{:x}}}'", value as u32));
44+
45+
Some(())
46+
}

src/tools/rust-analyzer/crates/ide-assists/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,7 @@ mod handlers {
119119
mod change_visibility;
120120
mod convert_bool_then;
121121
mod convert_bool_to_enum;
122+
mod convert_char_literal;
122123
mod convert_closure_to_fn;
123124
mod convert_comment_block;
124125
mod convert_comment_from_or_to_doc;
@@ -256,6 +257,7 @@ mod handlers {
256257
convert_bool_then::convert_bool_then_to_if,
257258
convert_bool_then::convert_if_to_bool_then,
258259
convert_bool_to_enum::convert_bool_to_enum,
260+
convert_char_literal::convert_char_literal,
259261
convert_closure_to_fn::convert_closure_to_fn,
260262
convert_comment_block::convert_comment_block,
261263
convert_comment_from_or_to_doc::convert_comment_from_or_to_doc,

0 commit comments

Comments
 (0)