Skip to content

Commit 4b49c7b

Browse files
Merge pull request #20354 from A4-Tacks/clean-lit-stmt-remove-dbg
Add remove literal dbg stmt for remove_dbg
2 parents 8241ec6 + 75fd004 commit 4b49c7b

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

crates/ide-assists/src/handlers/remove_dbg.rs

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,16 @@ fn compute_dbg_replacement(
112112
}
113113
}
114114
}
115+
// dbg!(2, 'x', &x, x, ...);
116+
exprs if ast::ExprStmt::can_cast(parent.kind()) && exprs.iter().all(pure_expr) => {
117+
let mut replace = vec![parent.clone().into()];
118+
if let Some(prev_sibling) = parent.prev_sibling_or_token()
119+
&& prev_sibling.kind() == syntax::SyntaxKind::WHITESPACE
120+
{
121+
replace.push(prev_sibling);
122+
}
123+
(replace, None)
124+
}
115125
// dbg!(expr0)
116126
[expr] => {
117127
// dbg!(expr, &parent);
@@ -163,6 +173,20 @@ fn compute_dbg_replacement(
163173
})
164174
}
165175

176+
fn pure_expr(expr: &ast::Expr) -> bool {
177+
match_ast! {
178+
match (expr.syntax()) {
179+
ast::Literal(_) => true,
180+
ast::RefExpr(it) => {
181+
matches!(it.expr(), Some(ast::Expr::PathExpr(p))
182+
if p.path().and_then(|p| p.as_single_name_ref()).is_some())
183+
},
184+
ast::PathExpr(it) => it.path().and_then(|it| it.as_single_name_ref()).is_some(),
185+
_ => false,
186+
}
187+
}
188+
}
189+
166190
fn replace_nested_dbgs(expanded: ast::Expr) -> ast::Expr {
167191
if let ast::Expr::MacroExpr(mac) = &expanded {
168192
// Special-case when `expanded` itself is `dbg!()` since we cannot replace the whole tree
@@ -231,6 +255,32 @@ mod tests {
231255
check("dbg!{$01 + 1}", "1 + 1");
232256
}
233257

258+
#[test]
259+
fn test_remove_simple_dbg_statement() {
260+
check_assist(
261+
remove_dbg,
262+
r#"
263+
fn foo() {
264+
let n = 2;
265+
$0dbg!(3);
266+
dbg!(2.6);
267+
dbg!(1, 2.5);
268+
dbg!('x');
269+
dbg!(&n);
270+
dbg!(n);
271+
// needless comment
272+
dbg!("foo");$0
273+
}
274+
"#,
275+
r#"
276+
fn foo() {
277+
let n = 2;
278+
// needless comment
279+
}
280+
"#,
281+
);
282+
}
283+
234284
#[test]
235285
fn test_remove_dbg_not_applicable() {
236286
check_assist_not_applicable(remove_dbg, "fn main() {$0vec![1, 2, 3]}");

0 commit comments

Comments
 (0)