]> git.lizzy.rs Git - rust.git/commitdiff
Don't wrap parens around expr in remove_dbg assist if its in conditions
authorLukas Wirth <lukastw97@gmail.com>
Fri, 20 Nov 2020 15:44:52 +0000 (16:44 +0100)
committerLukas Wirth <lukastw97@gmail.com>
Fri, 20 Nov 2020 16:28:56 +0000 (17:28 +0100)
crates/assists/src/handlers/remove_dbg.rs

index 9731344b8687351c9a68a4309e91396c46d4b565..eae6367c112e2091e18c254d84f86a72bb2d395e 100644 (file)
@@ -1,6 +1,6 @@
 use syntax::{
     ast::{self, AstNode},
-    SyntaxElement, SyntaxKind, TextRange, TextSize, T,
+    match_ast, SyntaxElement, SyntaxKind, TextRange, TextSize, T,
 };
 
 use crate::{AssistContext, AssistId, AssistKind, Assists};
@@ -49,12 +49,29 @@ fn adjusted_macro_contents(macro_call: &ast::MacroCall) -> Option<String> {
         macro_text_with_brackets.len() - TextSize::of(')'),
     ));
 
-    let is_leaf = macro_call.syntax().next_sibling().is_none();
-    Some(if !is_leaf && needs_parentheses_around_macro_contents(contents) {
-        format!("({})", macro_text_in_brackets)
-    } else {
-        macro_text_in_brackets.to_string()
-    })
+    Some(
+        if !is_leaf_or_control_flow_expr(macro_call)
+            && needs_parentheses_around_macro_contents(contents)
+        {
+            format!("({})", macro_text_in_brackets)
+        } else {
+            macro_text_in_brackets.to_string()
+        },
+    )
+}
+
+fn is_leaf_or_control_flow_expr(macro_call: &ast::MacroCall) -> bool {
+    macro_call.syntax().next_sibling().is_none()
+        || match macro_call.syntax().parent() {
+            Some(parent) => match_ast! {
+                match parent {
+                    ast::Condition(_it) => true,
+                    ast::MatchExpr(_it) => true,
+                    _ => false,
+                }
+            },
+            None => false,
+        }
 }
 
 /// Verifies that the given macro_call actually matches the given name
@@ -361,4 +378,44 @@ fn test_remove_dbg_range_expr() {
             r#"let res = (foo..=bar).foo();"#,
         );
     }
+
+    #[test]
+    fn test_remove_dbg_followed_by_block() {
+        check_assist(
+            remove_dbg,
+            r#"fn foo() {
+    if <|>dbg!(x || y) {}
+}"#,
+            r#"fn foo() {
+    if x || y {}
+}"#,
+        );
+        check_assist(
+            remove_dbg,
+            r#"fn foo() {
+    while let foo = <|>dbg!(&x) {}
+}"#,
+            r#"fn foo() {
+    while let foo = &x {}
+}"#,
+        );
+        check_assist(
+            remove_dbg,
+            r#"fn foo() {
+    if let foo = <|>dbg!(&x) {}
+}"#,
+            r#"fn foo() {
+    if let foo = &x {}
+}"#,
+        );
+        check_assist(
+            remove_dbg,
+            r#"fn foo() {
+    match <|>dbg!(&x) {}
+}"#,
+            r#"fn foo() {
+    match &x {}
+}"#,
+        );
+    }
 }