if_let_chain: allow mixing in normal ifs as well

This commit is contained in:
Georg Brandl 2015-08-12 21:11:32 +02:00
parent dbd396db91
commit 4400aaed43
2 changed files with 33 additions and 17 deletions

View File

@ -69,17 +69,16 @@ impl ReturnPass {
// we need both a let-binding stmt and an expr
if_let_chain! {
[
Some(stmt) = block.stmts.last(),
StmtDecl(ref decl, _) = stmt.node,
DeclLocal(ref local) = decl.node,
Some(ref initexpr) = local.init,
PatIdent(_, Spanned { node: id, .. }, _) = local.pat.node,
Some(ref retexpr) = block.expr,
ExprPath(_, ref path) = retexpr.node
let Some(stmt) = block.stmts.last(),
let StmtDecl(ref decl, _) = stmt.node,
let DeclLocal(ref local) = decl.node,
let Some(ref initexpr) = local.init,
let PatIdent(_, Spanned { node: id, .. }, _) = local.pat.node,
let Some(ref retexpr) = block.expr,
let ExprPath(_, ref path) = retexpr.node,
match_path(path, &[&*id.name.as_str()])
], {
if match_path(path, &[&*id.name.as_str()]) {
self.emit_let_lint(cx, retexpr.span, initexpr.span);
}
self.emit_let_lint(cx, retexpr.span, initexpr.span);
}
}
}

View File

@ -93,9 +93,14 @@ pub fn walk_ptrs_ty<'t>(ty: ty::Ty<'t>) -> ty::Ty<'t> {
}
}
/// Produce a nested chain of if-lets from the patterns:
/// Produce a nested chain of if-lets and ifs from the patterns:
///
/// if_let_chain! {[Some(y) = x, Some(z) = y],
/// if_let_chain! {
/// [
/// Some(y) = x,
/// y.len() == 2,
/// Some(z) = y,
/// ],
/// {
/// block
/// }
@ -104,20 +109,32 @@ pub fn walk_ptrs_ty<'t>(ty: ty::Ty<'t>) -> ty::Ty<'t> {
/// becomes
///
/// if let Some(y) = x {
/// if let Some(z) = y {
/// block
/// if y.len() == 2 {
/// if let Some(z) = y {
/// block
/// }
/// }
/// }
#[macro_export]
macro_rules! if_let_chain {
([$pat:pat = $expr:expr, $($p2:pat = $e2:expr),+], $block:block) => {
([let $pat:pat = $expr:expr, $($tt:tt)+], $block:block) => {
if let $pat = $expr {
if_let_chain!{ [$($p2 = $e2),+], $block }
if_let_chain!{ [$($tt)+], $block }
}
};
([$pat:pat = $expr:expr], $block:block) => {
([let $pat:pat = $expr:expr], $block:block) => {
if let $pat = $expr {
$block
}
};
([$expr:expr, $($tt:tt)+], $block:block) => {
if $expr {
if_let_chain!{ [$($tt)+], $block }
}
};
([$expr:expr], $block:block) => {
if $expr {
$block
}
};
}