2 ast::{self, AstNode, AstToken},
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 parent = macro_call.syntax().parent();
29 let macro_text_range = if let Some(it) = parent.as_ref() {
30 if new_contents.is_empty() {
33 ast::BlockExpr(it) => {
35 .prev_sibling_or_token()
36 .and_then(whitespace_start)
37 .map(|start| TextRange::new(start, macro_call.syntax().text_range().end()))
38 .unwrap_or(macro_call.syntax().text_range())
40 ast::ExprStmt(it) => {
43 .prev_sibling_or_token()
44 .and_then(whitespace_start)
45 .unwrap_or(it.syntax().text_range().start());
46 let end = it.syntax().text_range().end();
48 TextRange::new(start, end)
50 _ => macro_call.syntax().text_range()
54 macro_call.syntax().text_range()
57 macro_call.syntax().text_range()
60 let macro_end = if macro_call.semicolon_token().is_some() {
61 macro_text_range.end() - TextSize::of(';')
63 macro_text_range.end()
67 AssistId("remove_dbg", AssistKind::Refactor),
72 TextRange::new(macro_text_range.start(), macro_end),
73 if new_contents.is_empty() && parent.and_then(ast::LetStmt::cast).is_some() {
74 ast::make::expr_unit().to_string()
83 fn whitespace_start(it: SyntaxElement) -> Option<TextSize> {
84 Some(it.into_token().and_then(ast::Whitespace::cast)?.syntax().text_range().start())
87 fn adjusted_macro_contents(macro_call: &ast::MacroCall) -> Option<String> {
88 let contents = get_valid_macrocall_contents(¯o_call, "dbg")?;
89 let macro_text_with_brackets = macro_call.token_tree()?.syntax().text();
90 let macro_text_in_brackets = macro_text_with_brackets.slice(TextRange::new(
92 macro_text_with_brackets.len() - TextSize::of(')'),
96 if !is_leaf_or_control_flow_expr(macro_call)
97 && needs_parentheses_around_macro_contents(contents)
99 format!("({})", macro_text_in_brackets)
101 macro_text_in_brackets.to_string()
106 fn is_leaf_or_control_flow_expr(macro_call: &ast::MacroCall) -> bool {
107 macro_call.syntax().next_sibling().is_none()
108 || match macro_call.syntax().parent() {
109 Some(parent) => match_ast! {
111 ast::Condition(_it) => true,
112 ast::MatchExpr(_it) => true,
120 /// Verifies that the given macro_call actually matches the given name
121 /// and contains proper ending tokens, then returns the contents between the ending tokens
122 fn get_valid_macrocall_contents(
123 macro_call: &ast::MacroCall,
125 ) -> Option<Vec<SyntaxElement>> {
126 let path = macro_call.path()?;
127 let name_ref = path.segment()?.name_ref()?;
129 // Make sure it is actually a dbg-macro call, dbg followed by !
130 let excl = path.syntax().next_sibling_or_token()?;
131 if name_ref.text() != macro_name || excl.kind() != T![!] {
135 let mut children_with_tokens = macro_call.token_tree()?.syntax().children_with_tokens();
136 let first_child = children_with_tokens.next()?;
137 let mut contents_between_brackets = children_with_tokens.collect::<Vec<_>>();
138 let last_child = contents_between_brackets.pop()?;
140 match (first_child.kind(), last_child.kind()) {
141 (T!['('], T![')']) | (T!['['], T![']']) | (T!['{'], T!['}']) => {
142 Some(contents_between_brackets)
148 fn needs_parentheses_around_macro_contents(macro_contents: Vec<SyntaxElement>) -> bool {
149 if macro_contents.len() < 2 {
152 let mut macro_contents = macro_contents.into_iter().peekable();
153 let mut unpaired_brackets_in_contents = Vec::new();
154 while let Some(element) = macro_contents.next() {
155 match element.kind() {
156 T!['('] | T!['['] | T!['{'] => unpaired_brackets_in_contents.push(element),
158 if !matches!(unpaired_brackets_in_contents.pop(), Some(correct_bracket) if correct_bracket.kind() == T!['('])
164 if !matches!(unpaired_brackets_in_contents.pop(), Some(correct_bracket) if correct_bracket.kind() == T!['['])
170 if !matches!(unpaired_brackets_in_contents.pop(), Some(correct_bracket) if correct_bracket.kind() == T!['{'])
176 let symbol_not_in_bracket = unpaired_brackets_in_contents.is_empty();
177 if symbol_not_in_bracket
178 && symbol_kind != T![:] // paths
179 && (symbol_kind != T![.] // field/method access
180 || macro_contents // range expressions consist of two SyntaxKind::Dot in macro invocations
182 .map(|element| element.kind() == T![.])
184 && symbol_kind != T![?] // try operator
185 && (symbol_kind.is_punct() || symbol_kind == T![as])
192 !unpaired_brackets_in_contents.is_empty()
197 use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};
202 fn test_remove_dbg() {
203 check_assist(remove_dbg, "$0dbg!(1 + 1)", "1 + 1");
205 check_assist(remove_dbg, "dbg!$0((1 + 1))", "(1 + 1)");
207 check_assist(remove_dbg, "dbg!(1 $0+ 1)", "1 + 1");
209 check_assist(remove_dbg, "let _ = $0dbg!(1 + 1)", "let _ = 1 + 1");
215 if let Some(_) = dbg!(n.$0checked_sub(4)) {
222 if let Some(_) = n.checked_sub(4) {
229 check_assist(remove_dbg, "$0dbg!(Foo::foo_test()).bar()", "Foo::foo_test().bar()");
233 fn test_remove_dbg_with_brackets_and_braces() {
234 check_assist(remove_dbg, "dbg![$01 + 1]", "1 + 1");
235 check_assist(remove_dbg, "dbg!{$01 + 1}", "1 + 1");
239 fn test_remove_dbg_not_applicable() {
240 check_assist_not_applicable(remove_dbg, "$0vec![1, 2, 3]");
241 check_assist_not_applicable(remove_dbg, "$0dbg(5, 6, 7)");
242 check_assist_not_applicable(remove_dbg, "$0dbg!(5, 6, 7");
246 fn test_remove_dbg_target() {
251 if let Some(_) = dbg!(n.$0checked_sub(4)) {
256 "dbg!(n.checked_sub(4))",
261 fn test_remove_dbg_keep_semicolon() {
262 // https://github.com/rust-analyzer/rust-analyzer/issues/5129#issuecomment-651399779
264 // adding a comment at the end of the line makes
265 // the ast::MacroCall to include the semicolon at the end
268 r#"let res = $0dbg!(1 * 20); // needless comment"#,
269 r#"let res = 1 * 20; // needless comment"#,
274 fn remove_dbg_from_non_leaf_simple_expression() {
280 while dbg!$0(a) < 10000 {
297 fn test_remove_dbg_keep_expression() {
300 r#"let res = $0dbg!(a + b).foo();"#,
301 r#"let res = (a + b).foo();"#,
304 check_assist(remove_dbg, r#"let res = $0dbg!(2 + 2) * 5"#, r#"let res = (2 + 2) * 5"#);
305 check_assist(remove_dbg, r#"let res = $0dbg![2 + 2] * 5"#, r#"let res = (2 + 2) * 5"#);
309 fn test_remove_dbg_method_chaining() {
312 r#"let res = $0dbg!(foo().bar()).baz();"#,
313 r#"let res = foo().bar().baz();"#,
317 r#"let res = $0dbg!(foo.bar()).baz();"#,
318 r#"let res = foo.bar().baz();"#,
323 fn test_remove_dbg_field_chaining() {
324 check_assist(remove_dbg, r#"let res = $0dbg!(foo.bar).baz;"#, r#"let res = foo.bar.baz;"#);
328 fn test_remove_dbg_from_inside_fn() {
332 fn square(x: u32) -> u32 {
337 let x = square(dbg$0!(5 + 10));
346 fn square(x: u32) -> u32 {
351 let x = square(dbg$0!(5 + 10));
355 fn square(x: u32) -> u32 {
360 let x = square(5 + 10);
367 fn test_remove_dbg_try_expr() {
370 r#"let res = $0dbg!(result?).foo();"#,
371 r#"let res = result?.foo();"#,
376 fn test_remove_dbg_await_expr() {
379 r#"let res = $0dbg!(fut.await).foo();"#,
380 r#"let res = fut.await.foo();"#,
385 fn test_remove_dbg_as_cast() {
388 r#"let res = $0dbg!(3 as usize).foo();"#,
389 r#"let res = (3 as usize).foo();"#,
394 fn test_remove_dbg_index_expr() {
397 r#"let res = $0dbg!(array[3]).foo();"#,
398 r#"let res = array[3].foo();"#,
402 r#"let res = $0dbg!(tuple.3).foo();"#,
403 r#"let res = tuple.3.foo();"#,
408 fn test_remove_dbg_range_expr() {
411 r#"let res = $0dbg!(foo..bar).foo();"#,
412 r#"let res = (foo..bar).foo();"#,
416 r#"let res = $0dbg!(foo..=bar).foo();"#,
417 r#"let res = (foo..=bar).foo();"#,
422 fn test_remove_dbg_followed_by_block() {
435 while let foo = $0dbg!(&x) {}
438 while let foo = &x {}
444 if let foo = $0dbg!(&x) {}
462 fn test_remove_empty_dbg() {
463 check_assist(remove_dbg, r#"fn foo() { $0dbg!(); }"#, r#"fn foo() { }"#);
493 println!("Hello, world");
499 println!("Hello, world");