6 use crate::{Assist, AssistCtx, AssistId};
10 // Removes `dbg!()` macro call.
23 pub(crate) fn remove_dbg(ctx: AssistCtx) -> Option<Assist> {
24 let macro_call = ctx.find_node_at_offset::<ast::MacroCall>()?;
26 if !is_valid_macrocall(¯o_call, "dbg")? {
30 let macro_range = macro_call.syntax().text_range();
32 // If the cursor is inside the macro call, we'll try to maintain the cursor
33 // position by subtracting the length of dbg!( from the start of the file
34 // range, otherwise we'll default to using the start of the macro call
36 let file_range = ctx.frange.range;
38 let offset_start = file_range
40 .checked_sub(macro_range.start())
41 .unwrap_or_else(|| TextSize::from(0));
43 let dbg_size = TextSize::of("dbg!(");
45 if offset_start > dbg_size {
46 file_range.start() - dbg_size
53 let macro_args = macro_call.token_tree()?.syntax().clone();
55 let text = macro_args.text();
56 let without_parens = TextSize::of('(')..text.len() - TextSize::of(')');
57 text.slice(without_parens).to_string()
60 let target = macro_call.syntax().text_range();
61 ctx.add_assist(AssistId("remove_dbg"), "Remove dbg!()", target, |edit| {
62 edit.replace(macro_range, macro_content);
63 edit.set_cursor(cursor_pos);
67 /// Verifies that the given macro_call actually matches the given name
68 /// and contains proper ending tokens
69 fn is_valid_macrocall(macro_call: &ast::MacroCall, macro_name: &str) -> Option<bool> {
70 let path = macro_call.path()?;
71 let name_ref = path.segment()?.name_ref()?;
73 // Make sure it is actually a dbg-macro call, dbg followed by !
74 let excl = path.syntax().next_sibling_or_token()?;
76 if name_ref.text() != macro_name || excl.kind() != T![!] {
80 let node = macro_call.token_tree()?.syntax().clone();
81 let first_child = node.first_child_or_token()?;
82 let last_child = node.last_child_or_token()?;
84 match (first_child.kind(), last_child.kind()) {
85 (T!['('], T![')']) | (T!['['], T![']']) | (T!['{'], T!['}']) => Some(true),
93 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
96 fn test_remove_dbg() {
97 check_assist(remove_dbg, "<|>dbg!(1 + 1)", "<|>1 + 1");
99 check_assist(remove_dbg, "dbg!<|>((1 + 1))", "<|>(1 + 1)");
101 check_assist(remove_dbg, "dbg!(1 <|>+ 1)", "1 <|>+ 1");
103 check_assist(remove_dbg, "let _ = <|>dbg!(1 + 1)", "let _ = <|>1 + 1");
109 if let Some(_) = dbg!(n.<|>checked_sub(4)) {
116 if let Some(_) = n.<|>checked_sub(4) {
124 fn test_remove_dbg_with_brackets_and_braces() {
125 check_assist(remove_dbg, "dbg![<|>1 + 1]", "<|>1 + 1");
126 check_assist(remove_dbg, "dbg!{<|>1 + 1}", "<|>1 + 1");
130 fn test_remove_dbg_not_applicable() {
131 check_assist_not_applicable(remove_dbg, "<|>vec![1, 2, 3]");
132 check_assist_not_applicable(remove_dbg, "<|>dbg(5, 6, 7)");
133 check_assist_not_applicable(remove_dbg, "<|>dbg!(5, 6, 7");
137 fn remove_dbg_target() {
142 if let Some(_) = dbg!(n.<|>checked_sub(4)) {
147 "dbg!(n.checked_sub(4))",