refactor if-let lowering

mainly to get rid of unwraps
This commit is contained in:
Aleksey Kladov 2019-08-07 13:51:54 +02:00
parent 4d6475ada0
commit 39967a85e1

View file

@ -559,6 +559,7 @@ where
match expr.kind() { match expr.kind() {
ast::ExprKind::IfExpr(e) => { ast::ExprKind::IfExpr(e) => {
let then_branch = self.collect_block_opt(e.then_branch()); let then_branch = self.collect_block_opt(e.then_branch());
let else_branch = e.else_branch().map(|b| match b { let else_branch = e.else_branch().map(|b| match b {
ast::ElseBranch::Block(it) => self.collect_block(it), ast::ElseBranch::Block(it) => self.collect_block(it),
ast::ElseBranch::IfExpr(elif) => { ast::ElseBranch::IfExpr(elif) => {
@ -567,11 +568,14 @@ where
} }
}); });
if let Some(pat) = e.condition().and_then(|c| c.pat()) { let condition = match e.condition() {
None => self.exprs.alloc(Expr::Missing),
Some(condition) => match condition.pat() {
None => self.collect_expr_opt(condition.expr()),
// if let -- desugar to match // if let -- desugar to match
Some(pat) => {
let pat = self.collect_pat(pat); let pat = self.collect_pat(pat);
let match_expr = let match_expr = self.collect_expr_opt(condition.expr());
self.collect_expr_opt(e.condition().expect("checked above").expr());
let placeholder_pat = self.pats.alloc(Pat::Missing); let placeholder_pat = self.pats.alloc(Pat::Missing);
let arms = vec![ let arms = vec![
MatchArm { pats: vec![pat], expr: then_branch, guard: None }, MatchArm { pats: vec![pat], expr: then_branch, guard: None },
@ -581,11 +585,13 @@ where
guard: None, guard: None,
}, },
]; ];
self.alloc_expr(Expr::Match { expr: match_expr, arms }, syntax_ptr) return self
} else { .alloc_expr(Expr::Match { expr: match_expr, arms }, syntax_ptr);
let condition = self.collect_expr_opt(e.condition().and_then(|c| c.expr()));
self.alloc_expr(Expr::If { condition, then_branch, else_branch }, syntax_ptr)
} }
},
};
self.alloc_expr(Expr::If { condition, then_branch, else_branch }, syntax_ptr)
} }
ast::ExprKind::TryBlockExpr(e) => { ast::ExprKind::TryBlockExpr(e) => {
let body = self.collect_block_opt(e.try_body()); let body = self.collect_block_opt(e.try_body());