From 39967a85e1f04676062d46b04e7ac8399c57df66 Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Wed, 7 Aug 2019 13:51:54 +0200 Subject: refactor if-let lowering mainly to get rid of unwraps --- crates/ra_hir/src/expr.rs | 44 +++++++++++++++++++++++++------------------- 1 file changed, 25 insertions(+), 19 deletions(-) (limited to 'crates/ra_hir') diff --git a/crates/ra_hir/src/expr.rs b/crates/ra_hir/src/expr.rs index 9fea70dda..b59787a83 100644 --- a/crates/ra_hir/src/expr.rs +++ b/crates/ra_hir/src/expr.rs @@ -559,6 +559,7 @@ where match expr.kind() { ast::ExprKind::IfExpr(e) => { let then_branch = self.collect_block_opt(e.then_branch()); + let else_branch = e.else_branch().map(|b| match b { ast::ElseBranch::Block(it) => self.collect_block(it), ast::ElseBranch::IfExpr(elif) => { @@ -567,25 +568,30 @@ where } }); - if let Some(pat) = e.condition().and_then(|c| c.pat()) { - // if let -- desugar to match - let pat = self.collect_pat(pat); - let match_expr = - self.collect_expr_opt(e.condition().expect("checked above").expr()); - let placeholder_pat = self.pats.alloc(Pat::Missing); - let arms = vec![ - MatchArm { pats: vec![pat], expr: then_branch, guard: None }, - MatchArm { - pats: vec![placeholder_pat], - expr: else_branch.unwrap_or_else(|| self.empty_block()), - guard: None, - }, - ]; - self.alloc_expr(Expr::Match { expr: match_expr, arms }, syntax_ptr) - } else { - 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) - } + 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 + Some(pat) => { + let pat = self.collect_pat(pat); + let match_expr = self.collect_expr_opt(condition.expr()); + let placeholder_pat = self.pats.alloc(Pat::Missing); + let arms = vec![ + MatchArm { pats: vec![pat], expr: then_branch, guard: None }, + MatchArm { + pats: vec![placeholder_pat], + expr: else_branch.unwrap_or_else(|| self.empty_block()), + guard: None, + }, + ]; + return self + .alloc_expr(Expr::Match { expr: match_expr, arms }, syntax_ptr); + } + }, + }; + + self.alloc_expr(Expr::If { condition, then_branch, else_branch }, syntax_ptr) } ast::ExprKind::TryBlockExpr(e) => { let body = self.collect_block_opt(e.try_body()); -- cgit v1.2.3