3 match_ast, SyntaxElement, TextRange, TextSize, T,
6 use crate::{AssistContext, AssistId, AssistKind, Assists};
10 // Removes `dbg!()` macro call.
23 pub(crate) fn remove_dbg(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
24 let macro_call = ctx.find_node_at_offset::<ast::MacroCall>()?;
25 let new_contents = adjusted_macro_contents(¯o_call)?;
27 let macro_text_range = macro_call.syntax().text_range();
28 let macro_end = if macro_call.semicolon_token().is_some() {
29 macro_text_range.end() - TextSize::of(';')
31 macro_text_range.end()
35 AssistId("remove_dbg", AssistKind::Refactor),
39 builder.replace(TextRange::new(macro_text_range.start(), macro_end), new_contents);
44 fn adjusted_macro_contents(macro_call: &ast::MacroCall) -> Option<String> {
45 let contents = get_valid_macrocall_contents(¯o_call, "dbg")?;
46 let macro_text_with_brackets = macro_call.token_tree()?.syntax().text();
47 let macro_text_in_brackets = macro_text_with_brackets.slice(TextRange::new(
49 macro_text_with_brackets.len() - TextSize::of(')'),
53 if !is_leaf_or_control_flow_expr(macro_call)
54 && needs_parentheses_around_macro_contents(contents)
56 format!("({})", macro_text_in_brackets)
58 macro_text_in_brackets.to_string()
63 fn is_leaf_or_control_flow_expr(macro_call: &ast::MacroCall) -> bool {
64 macro_call.syntax().next_sibling().is_none()
65 || match macro_call.syntax().parent() {
66 Some(parent) => match_ast! {
68 ast::Condition(_it) => true,
69 ast::MatchExpr(_it) => true,
77 /// Verifies that the given macro_call actually matches the given name
78 /// and contains proper ending tokens, then returns the contents between the ending tokens
79 fn get_valid_macrocall_contents(
80 macro_call: &ast::MacroCall,
82 ) -> Option<Vec<SyntaxElement>> {
83 let path = macro_call.path()?;
84 let name_ref = path.segment()?.name_ref()?;
86 // Make sure it is actually a dbg-macro call, dbg followed by !
87 let excl = path.syntax().next_sibling_or_token()?;
88 if name_ref.text() != macro_name || excl.kind() != T![!] {
92 let mut children_with_tokens = macro_call.token_tree()?.syntax().children_with_tokens();
93 let first_child = children_with_tokens.next()?;
94 let mut contents_between_brackets = children_with_tokens.collect::<Vec<_>>();
95 let last_child = contents_between_brackets.pop()?;
97 if contents_between_brackets.is_empty() {
100 match (first_child.kind(), last_child.kind()) {
101 (T!['('], T![')']) | (T!['['], T![']']) | (T!['{'], T!['}']) => {
102 Some(contents_between_brackets)
109 fn needs_parentheses_around_macro_contents(macro_contents: Vec<SyntaxElement>) -> bool {
110 if macro_contents.len() < 2 {
113 let mut macro_contents = macro_contents.into_iter().peekable();
114 let mut unpaired_brackets_in_contents = Vec::new();
115 while let Some(element) = macro_contents.next() {
116 match element.kind() {
117 T!['('] | T!['['] | T!['{'] => unpaired_brackets_in_contents.push(element),
119 if !matches!(unpaired_brackets_in_contents.pop(), Some(correct_bracket) if correct_bracket.kind() == T!['('])
125 if !matches!(unpaired_brackets_in_contents.pop(), Some(correct_bracket) if correct_bracket.kind() == T!['['])
131 if !matches!(unpaired_brackets_in_contents.pop(), Some(correct_bracket) if correct_bracket.kind() == T!['{'])
137 let symbol_not_in_bracket = unpaired_brackets_in_contents.is_empty();
138 if symbol_not_in_bracket
139 && symbol_kind != T![:] // paths
140 && (symbol_kind != T![.] // field/method access
141 || macro_contents // range expressions consist of two SyntaxKind::Dot in macro invocations
143 .map(|element| element.kind() == T![.])
145 && symbol_kind != T![?] // try operator
146 && (symbol_kind.is_punct() || symbol_kind == T![as])
153 !unpaired_brackets_in_contents.is_empty()
158 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
163 fn test_remove_dbg() {
164 check_assist(remove_dbg, "$0dbg!(1 + 1)", "1 + 1");
166 check_assist(remove_dbg, "dbg!$0((1 + 1))", "(1 + 1)");
168 check_assist(remove_dbg, "dbg!(1 $0+ 1)", "1 + 1");
170 check_assist(remove_dbg, "let _ = $0dbg!(1 + 1)", "let _ = 1 + 1");
176 if let Some(_) = dbg!(n.$0checked_sub(4)) {
183 if let Some(_) = n.checked_sub(4) {
190 check_assist(remove_dbg, "$0dbg!(Foo::foo_test()).bar()", "Foo::foo_test().bar()");
194 fn test_remove_dbg_with_brackets_and_braces() {
195 check_assist(remove_dbg, "dbg![$01 + 1]", "1 + 1");
196 check_assist(remove_dbg, "dbg!{$01 + 1}", "1 + 1");
200 fn test_remove_dbg_not_applicable() {
201 check_assist_not_applicable(remove_dbg, "$0vec![1, 2, 3]");
202 check_assist_not_applicable(remove_dbg, "$0dbg(5, 6, 7)");
203 check_assist_not_applicable(remove_dbg, "$0dbg!(5, 6, 7");
207 fn test_remove_dbg_target() {
212 if let Some(_) = dbg!(n.$0checked_sub(4)) {
217 "dbg!(n.checked_sub(4))",
222 fn test_remove_dbg_keep_semicolon() {
223 // https://github.com/rust-analyzer/rust-analyzer/issues/5129#issuecomment-651399779
225 // adding a comment at the end of the line makes
226 // the ast::MacroCall to include the semicolon at the end
229 r#"let res = $0dbg!(1 * 20); // needless comment"#,
230 r#"let res = 1 * 20; // needless comment"#,
235 fn remove_dbg_from_non_leaf_simple_expression() {
241 while dbg!$0(a) < 10000 {
258 fn test_remove_dbg_keep_expression() {
261 r#"let res = $0dbg!(a + b).foo();"#,
262 r#"let res = (a + b).foo();"#,
265 check_assist(remove_dbg, r#"let res = $0dbg!(2 + 2) * 5"#, r#"let res = (2 + 2) * 5"#);
266 check_assist(remove_dbg, r#"let res = $0dbg![2 + 2] * 5"#, r#"let res = (2 + 2) * 5"#);
270 fn test_remove_dbg_method_chaining() {
273 r#"let res = $0dbg!(foo().bar()).baz();"#,
274 r#"let res = foo().bar().baz();"#,
278 r#"let res = $0dbg!(foo.bar()).baz();"#,
279 r#"let res = foo.bar().baz();"#,
284 fn test_remove_dbg_field_chaining() {
285 check_assist(remove_dbg, r#"let res = $0dbg!(foo.bar).baz;"#, r#"let res = foo.bar.baz;"#);
289 fn test_remove_dbg_from_inside_fn() {
293 fn square(x: u32) -> u32 {
298 let x = square(dbg$0!(5 + 10));
307 fn square(x: u32) -> u32 {
312 let x = square(dbg$0!(5 + 10));
316 fn square(x: u32) -> u32 {
321 let x = square(5 + 10);
328 fn test_remove_dbg_try_expr() {
331 r#"let res = $0dbg!(result?).foo();"#,
332 r#"let res = result?.foo();"#,
337 fn test_remove_dbg_await_expr() {
340 r#"let res = $0dbg!(fut.await).foo();"#,
341 r#"let res = fut.await.foo();"#,
346 fn test_remove_dbg_as_cast() {
349 r#"let res = $0dbg!(3 as usize).foo();"#,
350 r#"let res = (3 as usize).foo();"#,
355 fn test_remove_dbg_index_expr() {
358 r#"let res = $0dbg!(array[3]).foo();"#,
359 r#"let res = array[3].foo();"#,
363 r#"let res = $0dbg!(tuple.3).foo();"#,
364 r#"let res = tuple.3.foo();"#,
369 fn test_remove_dbg_range_expr() {
372 r#"let res = $0dbg!(foo..bar).foo();"#,
373 r#"let res = (foo..bar).foo();"#,
377 r#"let res = $0dbg!(foo..=bar).foo();"#,
378 r#"let res = (foo..=bar).foo();"#,
383 fn test_remove_dbg_followed_by_block() {
396 while let foo = $0dbg!(&x) {}
399 while let foo = &x {}
405 if let foo = $0dbg!(&x) {}