Skip to content

Commit 1973e94

Browse files
committed
Allow explicit returns with cfg attributes
1 parent 501ff22 commit 1973e94

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

clippy_lints/src/returns.rs

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,10 +58,21 @@ impl ReturnPass {
5858

5959
// Check a the final expression in a block if it's a return.
6060
fn check_final_expr(&mut self, cx: &EarlyContext, expr: &ast::Expr, span: Option<Span>) {
61+
fn attr_is_cfg(attr: &ast::Attribute) -> bool {
62+
if let ast::MetaItemKind::List(ref key, _) = attr.node.value.node {
63+
*key == "cfg"
64+
} else {
65+
false
66+
}
67+
}
68+
6169
match expr.node {
6270
// simple return is always "bad"
6371
ast::ExprKind::Ret(Some(ref inner)) => {
64-
self.emit_return_lint(cx, span.expect("`else return` is not possible"), inner.span);
72+
// allow `#[cfg(a)] return a; #[cfg(b)] return b;`
73+
if !expr.attrs.iter().any(attr_is_cfg) {
74+
self.emit_return_lint(cx, span.expect("`else return` is not possible"), inner.span);
75+
}
6576
}
6677
// a whole block? check it!
6778
ast::ExprKind::Block(ref block) => {

tests/run-pass/needless_return.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
#[deny(warnings)]
2+
fn cfg_return() -> i32 {
3+
#[cfg(msvc)] return 1;
4+
#[cfg(not(msvc))] return 2;
5+
}
6+
7+
fn main() {
8+
cfg_return();
9+
}

0 commit comments

Comments
 (0)