Skip to content

Commit e2908df

Browse files
authored
Merge pull request #1347 from sinkuu/conditional_returns
Allow explicit returns with cfg attributes
2 parents 501ff22 + 5d40965 commit e2908df

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

clippy_lints/src/returns.rs

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,10 @@ impl ReturnPass {
6161
match expr.node {
6262
// simple return is always "bad"
6363
ast::ExprKind::Ret(Some(ref inner)) => {
64-
self.emit_return_lint(cx, span.expect("`else return` is not possible"), inner.span);
64+
// allow `#[cfg(a)] return a; #[cfg(b)] return b;`
65+
if !expr.attrs.iter().any(attr_is_cfg) {
66+
self.emit_return_lint(cx, span.expect("`else return` is not possible"), inner.span);
67+
}
6568
}
6669
// a whole block? check it!
6770
ast::ExprKind::Block(ref block) => {
@@ -105,6 +108,7 @@ impl ReturnPass {
105108
let ast::StmtKind::Expr(ref retexpr) = retexpr.node,
106109
let Some(stmt) = it.next_back(),
107110
let ast::StmtKind::Local(ref local) = stmt.node,
111+
!local.attrs.iter().any(attr_is_cfg),
108112
let Some(ref initexpr) = local.init,
109113
let ast::PatKind::Ident(_, Spanned { node: id, .. }, _) = local.pat.node,
110114
let ast::ExprKind::Path(_, ref path) = retexpr.node,
@@ -140,3 +144,12 @@ impl EarlyLintPass for ReturnPass {
140144
self.check_let_return(cx, block);
141145
}
142146
}
147+
148+
fn attr_is_cfg(attr: &ast::Attribute) -> bool {
149+
if let ast::MetaItemKind::List(ref key, _) = attr.node.value.node {
150+
*key == "cfg"
151+
} else {
152+
false
153+
}
154+
}
155+

tests/run-pass/returns.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
#[deny(warnings)]
2+
fn cfg_return() -> i32 {
3+
#[cfg(unix)] return 1;
4+
#[cfg(not(unix))] return 2;
5+
}
6+
7+
#[deny(warnings)]
8+
fn cfg_let_and_return() -> i32 {
9+
#[cfg(unix)]
10+
let x = 1;
11+
#[cfg(not(unix))]
12+
let x = 2;
13+
x
14+
}
15+
16+
fn main() {
17+
cfg_return();
18+
cfg_let_and_return();
19+
}

0 commit comments

Comments
 (0)