Skip to content

Commit 7dac0ed

Browse files
committed
question_mark: Lint only early returns
1 parent bfc1779 commit 7dac0ed

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

clippy_lints/src/question_mark.rs

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -146,9 +146,28 @@ impl Pass {
146146
}
147147
}
148148

149-
// Check if the block has an implicit return expression
150-
if let Some(ref ret_expr) = block.expr {
151-
return Some(ret_expr.clone());
149+
// Check for `return` without a semicolon.
150+
//
151+
// ```rust
152+
// let _ = if self.opt.is_none() {
153+
// /* no stmts here */
154+
// return None
155+
// } else {
156+
// self.opt
157+
// };
158+
// ```
159+
//
160+
// This can be rewritten as:
161+
//
162+
// ```rust
163+
// let _ = self.opt?;
164+
// ```
165+
if_chain! {
166+
if block.stmts.len() == 0;
167+
if let Some(ExprKind::Ret(Some(ret_expr))) = block.expr.as_ref().map(|e| &e.node);
168+
then {
169+
return Some(ret_expr.clone());
170+
}
152171
}
153172

154173
None

tests/ui/question_mark.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,12 @@ impl SomeStruct {
5757
self.opt
5858
};
5959

60+
let _ = if self.opt.is_none() {
61+
None
62+
} else {
63+
self.opt
64+
};
65+
6066
let _ = if self.opt.is_none() {
6167
return None;
6268
} else {

0 commit comments

Comments
 (0)