]> git.lizzy.rs Git - rust.git/blob - src/librustc/hir/lowering/expr.rs
87462e94f430d566e6d5e1213287e351367e0f58
[rust.git] / src / librustc / hir / lowering / expr.rs
1 use super::{LoweringContext, ParamMode, ParenthesizedGenericArgs, ImplTraitContext};
2 use crate::hir::{self, HirVec};
3 use crate::hir::def::Res;
4 use crate::hir::ptr::P;
5
6 use rustc_data_structures::thin_vec::ThinVec;
7
8 use syntax::attr;
9 use syntax::ptr::P as AstP;
10 use syntax::ast::*;
11 use syntax::source_map::{respan, DesugaringKind, Span, Spanned};
12 use syntax::symbol::{sym, Symbol};
13
14 impl LoweringContext<'_> {
15     fn lower_exprs(&mut self, exprs: &[AstP<Expr>]) -> HirVec<hir::Expr> {
16         exprs.iter().map(|x| self.lower_expr(x)).collect()
17     }
18
19     pub(super) fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
20         let kind = match e.node {
21             ExprKind::Box(ref inner) => hir::ExprKind::Box(P(self.lower_expr(inner))),
22             ExprKind::Array(ref exprs) => hir::ExprKind::Array(self.lower_exprs(exprs)),
23             ExprKind::Repeat(ref expr, ref count) => {
24                 let expr = P(self.lower_expr(expr));
25                 let count = self.lower_anon_const(count);
26                 hir::ExprKind::Repeat(expr, count)
27             }
28             ExprKind::Tup(ref elts) => hir::ExprKind::Tup(self.lower_exprs(elts)),
29             ExprKind::Call(ref f, ref args) => {
30                 let f = P(self.lower_expr(f));
31                 hir::ExprKind::Call(f, self.lower_exprs(args))
32             }
33             ExprKind::MethodCall(ref seg, ref args) => {
34                 let hir_seg = P(self.lower_path_segment(
35                     e.span,
36                     seg,
37                     ParamMode::Optional,
38                     0,
39                     ParenthesizedGenericArgs::Err,
40                     ImplTraitContext::disallowed(),
41                     None,
42                 ));
43                 let args = self.lower_exprs(args);
44                 hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args)
45             }
46             ExprKind::Binary(binop, ref lhs, ref rhs) => {
47                 let binop = self.lower_binop(binop);
48                 let lhs = P(self.lower_expr(lhs));
49                 let rhs = P(self.lower_expr(rhs));
50                 hir::ExprKind::Binary(binop, lhs, rhs)
51             }
52             ExprKind::Unary(op, ref ohs) => {
53                 let op = self.lower_unop(op);
54                 let ohs = P(self.lower_expr(ohs));
55                 hir::ExprKind::Unary(op, ohs)
56             }
57             ExprKind::Lit(ref l) => hir::ExprKind::Lit(respan(l.span, l.node.clone())),
58             ExprKind::Cast(ref expr, ref ty) => {
59                 let expr = P(self.lower_expr(expr));
60                 hir::ExprKind::Cast(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
61             }
62             ExprKind::Type(ref expr, ref ty) => {
63                 let expr = P(self.lower_expr(expr));
64                 hir::ExprKind::Type(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
65             }
66             ExprKind::AddrOf(m, ref ohs) => {
67                 let m = self.lower_mutability(m);
68                 let ohs = P(self.lower_expr(ohs));
69                 hir::ExprKind::AddrOf(m, ohs)
70             }
71             ExprKind::Let(ref pat, ref scrutinee) => self.lower_expr_let(e.span, pat, scrutinee),
72             ExprKind::If(ref cond, ref then, ref else_opt) => {
73                 self.lower_expr_if(e.span, cond, then, else_opt.as_deref())
74             }
75             ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
76                 this.lower_expr_while_in_loop_scope(e.span, cond, body, opt_label)
77             }),
78             ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
79                 hir::ExprKind::Loop(
80                     this.lower_block(body, false),
81                     this.lower_label(opt_label),
82                     hir::LoopSource::Loop,
83                 )
84             }),
85             ExprKind::TryBlock(ref body) => self.lower_expr_try_block(body),
86             ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
87                 P(self.lower_expr(expr)),
88                 arms.iter().map(|x| self.lower_arm(x)).collect(),
89                 hir::MatchSource::Normal,
90             ),
91             ExprKind::Async(capture_clause, closure_node_id, ref block) => {
92                 self.make_async_expr(capture_clause, closure_node_id, None, block.span, |this| {
93                     this.with_new_scopes(|this| {
94                         let block = this.lower_block(block, false);
95                         this.expr_block(block, ThinVec::new())
96                     })
97                 })
98             }
99             ExprKind::Await(ref expr) => self.lower_expr_await(e.span, expr),
100             ExprKind::Closure(
101                 capture_clause, asyncness, movability, ref decl, ref body, fn_decl_span
102             ) => if let IsAsync::Async { closure_id, .. } = asyncness {
103                 self.lower_expr_async_closure(capture_clause, closure_id, decl, body, fn_decl_span)
104             } else {
105                 self.lower_expr_closure(capture_clause, movability, decl, body, fn_decl_span)
106             }
107             ExprKind::Block(ref blk, opt_label) => {
108                 hir::ExprKind::Block(self.lower_block(blk,
109                                                       opt_label.is_some()),
110                                                       self.lower_label(opt_label))
111             }
112             ExprKind::Assign(ref el, ref er) => {
113                 hir::ExprKind::Assign(P(self.lower_expr(el)), P(self.lower_expr(er)))
114             }
115             ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
116                 self.lower_binop(op),
117                 P(self.lower_expr(el)),
118                 P(self.lower_expr(er)),
119             ),
120             ExprKind::Field(ref el, ident) => hir::ExprKind::Field(P(self.lower_expr(el)), ident),
121             ExprKind::Index(ref el, ref er) => {
122                 hir::ExprKind::Index(P(self.lower_expr(el)), P(self.lower_expr(er)))
123             }
124             ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
125                 self.lower_expr_range_closed(e.span, e1, e2)
126             }
127             ExprKind::Range(ref e1, ref e2, lims) => {
128                 self.lower_expr_range(e.span, e1.as_deref(), e2.as_deref(), lims)
129             }
130             ExprKind::Path(ref qself, ref path) => {
131                 let qpath = self.lower_qpath(
132                     e.id,
133                     qself,
134                     path,
135                     ParamMode::Optional,
136                     ImplTraitContext::disallowed(),
137                 );
138                 hir::ExprKind::Path(qpath)
139             }
140             ExprKind::Break(opt_label, ref opt_expr) => {
141                 hir::ExprKind::Break(
142                     self.lower_jump_destination(e.id, opt_label),
143                     opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
144                 )
145             }
146             ExprKind::Continue(opt_label) => {
147                 hir::ExprKind::Continue(self.lower_jump_destination(e.id, opt_label))
148             }
149             ExprKind::Ret(ref e) => hir::ExprKind::Ret(e.as_ref().map(|x| P(self.lower_expr(x)))),
150             ExprKind::InlineAsm(ref asm) => self.lower_expr_asm(asm),
151             ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprKind::Struct(
152                 P(self.lower_qpath(
153                     e.id,
154                     &None,
155                     path,
156                     ParamMode::Optional,
157                     ImplTraitContext::disallowed(),
158                 )),
159                 fields.iter().map(|x| self.lower_field(x)).collect(),
160                 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
161             ),
162             ExprKind::Paren(ref ex) => {
163                 let mut ex = self.lower_expr(ex);
164                 // Include parens in span, but only if it is a super-span.
165                 if e.span.contains(ex.span) {
166                     ex.span = e.span;
167                 }
168                 // Merge attributes into the inner expression.
169                 let mut attrs = e.attrs.clone();
170                 attrs.extend::<Vec<_>>(ex.attrs.into());
171                 ex.attrs = attrs;
172                 return ex;
173             }
174
175             ExprKind::Yield(ref opt_expr) => self.lower_expr_yield(e.span, opt_expr.as_deref()),
176
177             ExprKind::Err => hir::ExprKind::Err,
178
179             // Desugar `ExprForLoop`
180             // from: `[opt_ident]: for <pat> in <head> <body>`
181             ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
182                 return self.lower_expr_for(e, pat, head, body, opt_label);
183             }
184             ExprKind::Try(ref sub_expr) => self.lower_expr_try(e.span, sub_expr),
185             ExprKind::Mac(_) => panic!("Shouldn't exist here"),
186         };
187
188         hir::Expr {
189             hir_id: self.lower_node_id(e.id),
190             node: kind,
191             span: e.span,
192             attrs: e.attrs.clone(),
193         }
194     }
195
196     fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
197         match u {
198             UnOp::Deref => hir::UnDeref,
199             UnOp::Not => hir::UnNot,
200             UnOp::Neg => hir::UnNeg,
201         }
202     }
203
204     fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
205         Spanned {
206             node: match b.node {
207                 BinOpKind::Add => hir::BinOpKind::Add,
208                 BinOpKind::Sub => hir::BinOpKind::Sub,
209                 BinOpKind::Mul => hir::BinOpKind::Mul,
210                 BinOpKind::Div => hir::BinOpKind::Div,
211                 BinOpKind::Rem => hir::BinOpKind::Rem,
212                 BinOpKind::And => hir::BinOpKind::And,
213                 BinOpKind::Or => hir::BinOpKind::Or,
214                 BinOpKind::BitXor => hir::BinOpKind::BitXor,
215                 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
216                 BinOpKind::BitOr => hir::BinOpKind::BitOr,
217                 BinOpKind::Shl => hir::BinOpKind::Shl,
218                 BinOpKind::Shr => hir::BinOpKind::Shr,
219                 BinOpKind::Eq => hir::BinOpKind::Eq,
220                 BinOpKind::Lt => hir::BinOpKind::Lt,
221                 BinOpKind::Le => hir::BinOpKind::Le,
222                 BinOpKind::Ne => hir::BinOpKind::Ne,
223                 BinOpKind::Ge => hir::BinOpKind::Ge,
224                 BinOpKind::Gt => hir::BinOpKind::Gt,
225             },
226             span: b.span,
227         }
228     }
229
230     /// Emit an error and lower `ast::ExprKind::Let(pat, scrutinee)` into:
231     /// ```rust
232     /// match scrutinee { pats => true, _ => false }
233     /// ```
234     fn lower_expr_let(&mut self, span: Span, pat: &Pat, scrutinee: &Expr) -> hir::ExprKind {
235         // If we got here, the `let` expression is not allowed.
236         self.sess
237             .struct_span_err(span, "`let` expressions are not supported here")
238             .note("only supported directly in conditions of `if`- and `while`-expressions")
239             .note("as well as when nested within `&&` and parenthesis in those conditions")
240             .emit();
241
242         // For better recovery, we emit:
243         // ```
244         // match scrutinee { pat => true, _ => false }
245         // ```
246         // While this doesn't fully match the user's intent, it has key advantages:
247         // 1. We can avoid using `abort_if_errors`.
248         // 2. We can typeck both `pat` and `scrutinee`.
249         // 3. `pat` is allowed to be refutable.
250         // 4. The return type of the block is `bool` which seems like what the user wanted.
251         let scrutinee = self.lower_expr(scrutinee);
252         let then_arm = {
253             let pat = self.lower_pat_top_hack(pat);
254             let expr = self.expr_bool(span, true);
255             self.arm(pat, P(expr))
256         };
257         let else_arm = {
258             let pat = self.pat_wild(span);
259             let expr = self.expr_bool(span, false);
260             self.arm(hir_vec![pat], P(expr))
261         };
262         hir::ExprKind::Match(
263             P(scrutinee),
264             vec![then_arm, else_arm].into(),
265             hir::MatchSource::Normal,
266         )
267     }
268
269     fn lower_expr_if(
270         &mut self,
271         span: Span,
272         cond: &Expr,
273         then: &Block,
274         else_opt: Option<&Expr>,
275     ) -> hir::ExprKind {
276         // FIXME(#53667): handle lowering of && and parens.
277
278         // `_ => else_block` where `else_block` is `{}` if there's `None`:
279         let else_pat = self.pat_wild(span);
280         let (else_expr, contains_else_clause) = match else_opt {
281             None => (self.expr_block_empty(span), false),
282             Some(els) => (self.lower_expr(els), true),
283         };
284         let else_arm = self.arm(hir_vec![else_pat], P(else_expr));
285
286         // Handle then + scrutinee:
287         let then_blk = self.lower_block(then, false);
288         let then_expr = self.expr_block(then_blk, ThinVec::new());
289         let (then_pat, scrutinee, desugar) = match cond.node {
290             // `<pat> => <then>`:
291             ExprKind::Let(ref pat, ref scrutinee) => {
292                 let scrutinee = self.lower_expr(scrutinee);
293                 let pat = self.lower_pat_top_hack(pat);
294                 (pat, scrutinee, hir::MatchSource::IfLetDesugar { contains_else_clause })
295             }
296             // `true => <then>`:
297             _ => {
298                 // Lower condition:
299                 let cond = self.lower_expr(cond);
300                 let span_block = self.mark_span_with_reason(
301                     DesugaringKind::CondTemporary,
302                     cond.span,
303                     None
304                 );
305                 // Wrap in a construct equivalent to `{ let _t = $cond; _t }`
306                 // to preserve drop semantics since `if cond { ... }` does not
307                 // let temporaries live outside of `cond`.
308                 let cond = self.expr_drop_temps(span_block, P(cond), ThinVec::new());
309                 let pat = self.pat_bool(span, true);
310                 (hir_vec![pat], cond, hir::MatchSource::IfDesugar { contains_else_clause })
311             }
312         };
313         let then_arm = self.arm(then_pat, P(then_expr));
314
315         hir::ExprKind::Match(P(scrutinee), vec![then_arm, else_arm].into(), desugar)
316     }
317
318     fn lower_expr_while_in_loop_scope(
319         &mut self,
320         span: Span,
321         cond: &Expr,
322         body: &Block,
323         opt_label: Option<Label>
324     ) -> hir::ExprKind {
325         // FIXME(#53667): handle lowering of && and parens.
326
327         // Note that the block AND the condition are evaluated in the loop scope.
328         // This is done to allow `break` from inside the condition of the loop.
329
330         // `_ => break`:
331         let else_arm = {
332             let else_pat = self.pat_wild(span);
333             let else_expr = self.expr_break(span, ThinVec::new());
334             self.arm(hir_vec![else_pat], else_expr)
335         };
336
337         // Handle then + scrutinee:
338         let then_blk = self.lower_block(body, false);
339         let then_expr = self.expr_block(then_blk, ThinVec::new());
340         let (then_pat, scrutinee, desugar, source) = match cond.node {
341             ExprKind::Let(ref pat, ref scrutinee) => {
342                 // to:
343                 //
344                 //   [opt_ident]: loop {
345                 //     match <sub_expr> {
346                 //       <pat> => <body>,
347                 //       _ => break
348                 //     }
349                 //   }
350                 let scrutinee = self.with_loop_condition_scope(|t| t.lower_expr(scrutinee));
351                 let pat = self.lower_pat_top_hack(pat);
352                 (pat, scrutinee, hir::MatchSource::WhileLetDesugar, hir::LoopSource::WhileLet)
353             }
354             _ => {
355                 // We desugar: `'label: while $cond $body` into:
356                 //
357                 // ```
358                 // 'label: loop {
359                 //     match DropTemps($cond) {
360                 //         true => $body,
361                 //         _ => break,
362                 //     }
363                 // }
364                 // ```
365
366                 // Lower condition:
367                 let cond = self.with_loop_condition_scope(|this| this.lower_expr(cond));
368                 let span_block = self.mark_span_with_reason(
369                     DesugaringKind::CondTemporary,
370                     cond.span,
371                     None,
372                 );
373                 // Wrap in a construct equivalent to `{ let _t = $cond; _t }`
374                 // to preserve drop semantics since `while cond { ... }` does not
375                 // let temporaries live outside of `cond`.
376                 let cond = self.expr_drop_temps(span_block, P(cond), ThinVec::new());
377                 // `true => <then>`:
378                 let pat = self.pat_bool(span, true);
379                 (hir_vec![pat], cond, hir::MatchSource::WhileDesugar, hir::LoopSource::While)
380             }
381         };
382         let then_arm = self.arm(then_pat, P(then_expr));
383
384         // `match <scrutinee> { ... }`
385         let match_expr = self.expr_match(
386             scrutinee.span,
387             P(scrutinee),
388             hir_vec![then_arm, else_arm],
389             desugar,
390         );
391
392         // `[opt_ident]: loop { ... }`
393         hir::ExprKind::Loop(
394             P(self.block_expr(P(match_expr))),
395             self.lower_label(opt_label),
396             source
397         )
398     }
399
400     fn lower_expr_try_block(&mut self, body: &Block) -> hir::ExprKind {
401         self.with_catch_scope(body.id, |this| {
402             let unstable_span = this.mark_span_with_reason(
403                 DesugaringKind::TryBlock,
404                 body.span,
405                 this.allow_try_trait.clone(),
406             );
407             let mut block = this.lower_block(body, true).into_inner();
408             let tail = block.expr.take().map_or_else(
409                 || this.expr_unit(this.sess.source_map().end_point(unstable_span)),
410                 |x: P<hir::Expr>| x.into_inner(),
411             );
412             block.expr = Some(this.wrap_in_try_constructor(sym::from_ok, tail, unstable_span));
413             hir::ExprKind::Block(P(block), None)
414         })
415     }
416
417     fn wrap_in_try_constructor(
418         &mut self,
419         method: Symbol,
420         e: hir::Expr,
421         unstable_span: Span,
422     ) -> P<hir::Expr> {
423         let path = &[sym::ops, sym::Try, method];
424         let from_err = P(self.expr_std_path(unstable_span, path, None, ThinVec::new()));
425         P(self.expr_call(e.span, from_err, hir_vec![e]))
426     }
427
428     fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
429         hir::Arm {
430             hir_id: self.next_id(),
431             attrs: self.lower_attrs(&arm.attrs),
432             pats: self.lower_pat_top_hack(&arm.pat),
433             guard: match arm.guard {
434                 Some(ref x) => Some(hir::Guard::If(P(self.lower_expr(x)))),
435                 _ => None,
436             },
437             body: P(self.lower_expr(&arm.body)),
438             span: arm.span,
439         }
440     }
441
442     /// HACK(or_patterns; Centril | dlrobertson): For now we don't push down top level or-patterns
443     /// `p | q` into `hir::PatKind::Or(...)` as post-lowering bits of the compiler are not ready
444     /// to deal with it. This should by fixed by pushing it down to HIR and then HAIR.
445     fn lower_pat_top_hack(&mut self, pat: &Pat) -> HirVec<P<hir::Pat>> {
446         match pat.node {
447             PatKind::Or(ref ps) => ps.iter().map(|x| self.lower_pat(x)).collect(),
448             _ => hir_vec![self.lower_pat(pat)],
449         }
450     }
451
452     pub(super) fn make_async_expr(
453         &mut self,
454         capture_clause: CaptureBy,
455         closure_node_id: NodeId,
456         ret_ty: Option<AstP<Ty>>,
457         span: Span,
458         body: impl FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
459     ) -> hir::ExprKind {
460         let capture_clause = self.lower_capture_clause(capture_clause);
461         let output = match ret_ty {
462             Some(ty) => FunctionRetTy::Ty(ty),
463             None => FunctionRetTy::Default(span),
464         };
465         let ast_decl = FnDecl {
466             inputs: vec![],
467             output,
468             c_variadic: false
469         };
470         let decl = self.lower_fn_decl(&ast_decl, None, /* impl trait allowed */ false, None);
471         let body_id = self.lower_fn_body(&ast_decl, |this| {
472             this.generator_kind = Some(hir::GeneratorKind::Async);
473             body(this)
474         });
475
476         // `static || -> <ret_ty> { body }`:
477         let generator_node = hir::ExprKind::Closure(
478             capture_clause,
479             decl,
480             body_id,
481             span,
482             Some(hir::GeneratorMovability::Static)
483         );
484         let generator = hir::Expr {
485             hir_id: self.lower_node_id(closure_node_id),
486             node: generator_node,
487             span,
488             attrs: ThinVec::new(),
489         };
490
491         // `future::from_generator`:
492         let unstable_span = self.mark_span_with_reason(
493             DesugaringKind::Async,
494             span,
495             self.allow_gen_future.clone(),
496         );
497         let gen_future = self.expr_std_path(
498             unstable_span,
499             &[sym::future, sym::from_generator],
500             None,
501             ThinVec::new()
502         );
503
504         // `future::from_generator(generator)`:
505         hir::ExprKind::Call(P(gen_future), hir_vec![generator])
506     }
507
508     /// Desugar `<expr>.await` into:
509     /// ```rust
510     /// match <expr> {
511     ///     mut pinned => loop {
512     ///         match ::std::future::poll_with_tls_context(unsafe {
513     ///             <::std::pin::Pin>::new_unchecked(&mut pinned)
514     ///         }) {
515     ///             ::std::task::Poll::Ready(result) => break result,
516     ///             ::std::task::Poll::Pending => {}
517     ///         }
518     ///         yield ();
519     ///     }
520     /// }
521     /// ```
522     fn lower_expr_await(&mut self, await_span: Span, expr: &Expr) -> hir::ExprKind {
523         match self.generator_kind {
524             Some(hir::GeneratorKind::Async) => {},
525             Some(hir::GeneratorKind::Gen) |
526             None => {
527                 let mut err = struct_span_err!(
528                     self.sess,
529                     await_span,
530                     E0728,
531                     "`await` is only allowed inside `async` functions and blocks"
532                 );
533                 err.span_label(await_span, "only allowed inside `async` functions and blocks");
534                 if let Some(item_sp) = self.current_item {
535                     err.span_label(item_sp, "this is not `async`");
536                 }
537                 err.emit();
538             }
539         }
540         let span = self.mark_span_with_reason(
541             DesugaringKind::Await,
542             await_span,
543             None,
544         );
545         let gen_future_span = self.mark_span_with_reason(
546             DesugaringKind::Await,
547             await_span,
548             self.allow_gen_future.clone(),
549         );
550
551         let pinned_ident = Ident::with_dummy_span(sym::pinned);
552         let (pinned_pat, pinned_pat_hid) = self.pat_ident_binding_mode(
553             span,
554             pinned_ident,
555             hir::BindingAnnotation::Mutable,
556         );
557
558         // ::std::future::poll_with_tls_context(unsafe {
559         //     ::std::pin::Pin::new_unchecked(&mut pinned)
560         // })`
561         let poll_expr = {
562             let pinned = P(self.expr_ident(span, pinned_ident, pinned_pat_hid));
563             let ref_mut_pinned = self.expr_mut_addr_of(span, pinned);
564             let pin_ty_id = self.next_id();
565             let new_unchecked_expr_kind = self.expr_call_std_assoc_fn(
566                 pin_ty_id,
567                 span,
568                 &[sym::pin, sym::Pin],
569                 "new_unchecked",
570                 hir_vec![ref_mut_pinned],
571             );
572             let new_unchecked = P(self.expr(span, new_unchecked_expr_kind, ThinVec::new()));
573             let unsafe_expr = self.expr_unsafe(new_unchecked);
574             P(self.expr_call_std_path(
575                 gen_future_span,
576                 &[sym::future, sym::poll_with_tls_context],
577                 hir_vec![unsafe_expr],
578             ))
579         };
580
581         // `::std::task::Poll::Ready(result) => break result`
582         let loop_node_id = self.sess.next_node_id();
583         let loop_hir_id = self.lower_node_id(loop_node_id);
584         let ready_arm = {
585             let x_ident = Ident::with_dummy_span(sym::result);
586             let (x_pat, x_pat_hid) = self.pat_ident(span, x_ident);
587             let x_expr = P(self.expr_ident(span, x_ident, x_pat_hid));
588             let ready_pat = self.pat_std_enum(
589                 span,
590                 &[sym::task, sym::Poll, sym::Ready],
591                 hir_vec![x_pat],
592             );
593             let break_x = self.with_loop_scope(loop_node_id, |this| {
594                 let expr_break = hir::ExprKind::Break(
595                     this.lower_loop_destination(None),
596                     Some(x_expr),
597                 );
598                 P(this.expr(await_span, expr_break, ThinVec::new()))
599             });
600             self.arm(hir_vec![ready_pat], break_x)
601         };
602
603         // `::std::task::Poll::Pending => {}`
604         let pending_arm = {
605             let pending_pat = self.pat_std_enum(
606                 span,
607                 &[sym::task, sym::Poll, sym::Pending],
608                 hir_vec![],
609             );
610             let empty_block = P(self.expr_block_empty(span));
611             self.arm(hir_vec![pending_pat], empty_block)
612         };
613
614         let inner_match_stmt = {
615             let match_expr = self.expr_match(
616                 span,
617                 poll_expr,
618                 hir_vec![ready_arm, pending_arm],
619                 hir::MatchSource::AwaitDesugar,
620             );
621             self.stmt_expr(span, match_expr)
622         };
623
624         let yield_stmt = {
625             let unit = self.expr_unit(span);
626             let yield_expr = self.expr(
627                 span,
628                 hir::ExprKind::Yield(P(unit), hir::YieldSource::Await),
629                 ThinVec::new(),
630             );
631             self.stmt_expr(span, yield_expr)
632         };
633
634         let loop_block = P(self.block_all(
635             span,
636             hir_vec![inner_match_stmt, yield_stmt],
637             None,
638         ));
639
640         // loop { .. }
641         let loop_expr = P(hir::Expr {
642             hir_id: loop_hir_id,
643             node: hir::ExprKind::Loop(
644                 loop_block,
645                 None,
646                 hir::LoopSource::Loop,
647             ),
648             span,
649             attrs: ThinVec::new(),
650         });
651
652         // mut pinned => loop { ... }
653         let pinned_arm = self.arm(hir_vec![pinned_pat], loop_expr);
654
655         // match <expr> {
656         //     mut pinned => loop { .. }
657         // }
658         let expr = P(self.lower_expr(expr));
659         hir::ExprKind::Match(expr, hir_vec![pinned_arm], hir::MatchSource::AwaitDesugar)
660     }
661
662     fn lower_expr_closure(
663         &mut self,
664         capture_clause: CaptureBy,
665         movability: Movability,
666         decl: &FnDecl,
667         body: &Expr,
668         fn_decl_span: Span,
669     ) -> hir::ExprKind {
670         // Lower outside new scope to preserve `is_in_loop_condition`.
671         let fn_decl = self.lower_fn_decl(decl, None, false, None);
672
673         self.with_new_scopes(|this| {
674             let prev = this.current_item;
675             this.current_item = Some(fn_decl_span);
676             let mut generator_kind = None;
677             let body_id = this.lower_fn_body(decl, |this| {
678                 let e = this.lower_expr(body);
679                 generator_kind = this.generator_kind;
680                 e
681             });
682             let generator_option = this.generator_movability_for_fn(
683                 &decl,
684                 fn_decl_span,
685                 generator_kind,
686                 movability,
687             );
688             let capture_clause = this.lower_capture_clause(capture_clause);
689             this.current_item = prev;
690             hir::ExprKind::Closure(
691                 capture_clause,
692                 fn_decl,
693                 body_id,
694                 fn_decl_span,
695                 generator_option,
696             )
697         })
698     }
699
700     fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
701         match c {
702             CaptureBy::Value => hir::CaptureByValue,
703             CaptureBy::Ref => hir::CaptureByRef,
704         }
705     }
706
707     fn generator_movability_for_fn(
708         &mut self,
709         decl: &FnDecl,
710         fn_decl_span: Span,
711         generator_kind: Option<hir::GeneratorKind>,
712         movability: Movability,
713     ) -> Option<hir::GeneratorMovability> {
714         match generator_kind {
715             Some(hir::GeneratorKind::Gen) =>  {
716                 if !decl.inputs.is_empty() {
717                     span_err!(
718                         self.sess,
719                         fn_decl_span,
720                         E0628,
721                         "generators cannot have explicit parameters"
722                     );
723                     self.sess.abort_if_errors();
724                 }
725                 Some(match movability {
726                     Movability::Movable => hir::GeneratorMovability::Movable,
727                     Movability::Static => hir::GeneratorMovability::Static,
728                 })
729             },
730             Some(hir::GeneratorKind::Async) => {
731                 bug!("non-`async` closure body turned `async` during lowering");
732             },
733             None => {
734                 if movability == Movability::Static {
735                     span_err!(
736                         self.sess,
737                         fn_decl_span,
738                         E0697,
739                         "closures cannot be static"
740                     );
741                 }
742                 None
743             },
744         }
745     }
746
747     fn lower_expr_async_closure(
748         &mut self,
749         capture_clause: CaptureBy,
750         closure_id: NodeId,
751         decl: &FnDecl,
752         body: &Expr,
753         fn_decl_span: Span,
754     ) -> hir::ExprKind {
755         let outer_decl = FnDecl {
756             inputs: decl.inputs.clone(),
757             output: FunctionRetTy::Default(fn_decl_span),
758             c_variadic: false,
759         };
760         // We need to lower the declaration outside the new scope, because we
761         // have to conserve the state of being inside a loop condition for the
762         // closure argument types.
763         let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
764
765         self.with_new_scopes(|this| {
766             // FIXME(cramertj): allow `async` non-`move` closures with arguments.
767             if capture_clause == CaptureBy::Ref && !decl.inputs.is_empty() {
768                 struct_span_err!(
769                     this.sess,
770                     fn_decl_span,
771                     E0708,
772                     "`async` non-`move` closures with parameters are not currently supported",
773                 )
774                 .help(
775                     "consider using `let` statements to manually capture \
776                     variables by reference before entering an `async move` closure"
777                 )
778                 .emit();
779             }
780
781             // Transform `async |x: u8| -> X { ... }` into
782             // `|x: u8| future_from_generator(|| -> X { ... })`.
783             let body_id = this.lower_fn_body(&outer_decl, |this| {
784                 let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
785                     Some(ty.clone())
786                 } else {
787                     None
788                 };
789                 let async_body = this.make_async_expr(
790                     capture_clause, closure_id, async_ret_ty, body.span,
791                     |this| {
792                         this.with_new_scopes(|this| this.lower_expr(body))
793                     }
794                 );
795                 this.expr(fn_decl_span, async_body, ThinVec::new())
796             });
797             hir::ExprKind::Closure(
798                 this.lower_capture_clause(capture_clause),
799                 fn_decl,
800                 body_id,
801                 fn_decl_span,
802                 None,
803             )
804         })
805     }
806
807     /// Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`.
808     fn lower_expr_range_closed(&mut self, span: Span, e1: &Expr, e2: &Expr) -> hir::ExprKind {
809         let id = self.next_id();
810         let e1 = self.lower_expr(e1);
811         let e2 = self.lower_expr(e2);
812         self.expr_call_std_assoc_fn(
813             id,
814             span,
815             &[sym::ops, sym::RangeInclusive],
816             "new",
817             hir_vec![e1, e2],
818         )
819     }
820
821     fn lower_expr_range(
822         &mut self,
823         span: Span,
824         e1: Option<&Expr>,
825         e2: Option<&Expr>,
826         lims: RangeLimits,
827     ) -> hir::ExprKind {
828         use syntax::ast::RangeLimits::*;
829
830         let path = match (e1, e2, lims) {
831             (None, None, HalfOpen) => sym::RangeFull,
832             (Some(..), None, HalfOpen) => sym::RangeFrom,
833             (None, Some(..), HalfOpen) => sym::RangeTo,
834             (Some(..), Some(..), HalfOpen) => sym::Range,
835             (None, Some(..), Closed) => sym::RangeToInclusive,
836             (Some(..), Some(..), Closed) => unreachable!(),
837             (_, None, Closed) => self.diagnostic()
838                 .span_fatal(span, "inclusive range with no end")
839                 .raise(),
840         };
841
842         let fields = e1.iter()
843             .map(|e| ("start", e))
844             .chain(e2.iter().map(|e| ("end", e)))
845             .map(|(s, e)| {
846                 let expr = P(self.lower_expr(&e));
847                 let ident = Ident::new(Symbol::intern(s), e.span);
848                 self.field(ident, expr, e.span)
849             })
850             .collect::<P<[hir::Field]>>();
851
852         let is_unit = fields.is_empty();
853         let struct_path = [sym::ops, path];
854         let struct_path = self.std_path(span, &struct_path, None, is_unit);
855         let struct_path = hir::QPath::Resolved(None, P(struct_path));
856
857         if is_unit {
858             hir::ExprKind::Path(struct_path)
859         } else {
860             hir::ExprKind::Struct(P(struct_path), fields, None)
861         }
862     }
863
864     fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
865         label.map(|label| hir::Label {
866             ident: label.ident,
867         })
868     }
869
870     fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
871         let target_id = match destination {
872             Some((id, _)) => {
873                 if let Some(loop_id) = self.resolver.get_label_res(id) {
874                     Ok(self.lower_node_id(loop_id))
875                 } else {
876                     Err(hir::LoopIdError::UnresolvedLabel)
877                 }
878             }
879             None => {
880                 self.loop_scopes
881                     .last()
882                     .cloned()
883                     .map(|id| Ok(self.lower_node_id(id)))
884                     .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
885                     .into()
886             }
887         };
888         hir::Destination {
889             label: self.lower_label(destination.map(|(_, label)| label)),
890             target_id,
891         }
892     }
893
894     fn lower_jump_destination(&mut self, id: NodeId, opt_label: Option<Label>) -> hir::Destination {
895         if self.is_in_loop_condition && opt_label.is_none() {
896             hir::Destination {
897                 label: None,
898                 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
899             }
900         } else {
901             self.lower_loop_destination(opt_label.map(|label| (id, label)))
902         }
903     }
904
905     fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
906     where
907         F: FnOnce(&mut LoweringContext<'_>) -> T,
908     {
909         let len = self.catch_scopes.len();
910         self.catch_scopes.push(catch_id);
911
912         let result = f(self);
913         assert_eq!(
914             len + 1,
915             self.catch_scopes.len(),
916             "catch scopes should be added and removed in stack order"
917         );
918
919         self.catch_scopes.pop().unwrap();
920
921         result
922     }
923
924     fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
925     where
926         F: FnOnce(&mut LoweringContext<'_>) -> T,
927     {
928         // We're no longer in the base loop's condition; we're in another loop.
929         let was_in_loop_condition = self.is_in_loop_condition;
930         self.is_in_loop_condition = false;
931
932         let len = self.loop_scopes.len();
933         self.loop_scopes.push(loop_id);
934
935         let result = f(self);
936         assert_eq!(
937             len + 1,
938             self.loop_scopes.len(),
939             "loop scopes should be added and removed in stack order"
940         );
941
942         self.loop_scopes.pop().unwrap();
943
944         self.is_in_loop_condition = was_in_loop_condition;
945
946         result
947     }
948
949     fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
950     where
951         F: FnOnce(&mut LoweringContext<'_>) -> T,
952     {
953         let was_in_loop_condition = self.is_in_loop_condition;
954         self.is_in_loop_condition = true;
955
956         let result = f(self);
957
958         self.is_in_loop_condition = was_in_loop_condition;
959
960         result
961     }
962
963     fn lower_expr_asm(&mut self, asm: &InlineAsm) -> hir::ExprKind {
964         let hir_asm = hir::InlineAsm {
965             inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
966             outputs: asm.outputs
967                 .iter()
968                 .map(|out| hir::InlineAsmOutput {
969                     constraint: out.constraint.clone(),
970                     is_rw: out.is_rw,
971                     is_indirect: out.is_indirect,
972                     span: out.expr.span,
973                 })
974                 .collect(),
975             asm: asm.asm.clone(),
976             asm_str_style: asm.asm_str_style,
977             clobbers: asm.clobbers.clone().into(),
978             volatile: asm.volatile,
979             alignstack: asm.alignstack,
980             dialect: asm.dialect,
981         };
982
983         let outputs = asm.outputs
984             .iter()
985             .map(|out| self.lower_expr(&out.expr))
986             .collect();
987
988         let inputs = asm.inputs
989             .iter()
990             .map(|&(_, ref input)| self.lower_expr(input))
991             .collect();
992
993         hir::ExprKind::InlineAsm(P(hir_asm), outputs, inputs)
994     }
995
996     fn lower_field(&mut self, f: &Field) -> hir::Field {
997         hir::Field {
998             hir_id: self.next_id(),
999             ident: f.ident,
1000             expr: P(self.lower_expr(&f.expr)),
1001             span: f.span,
1002             is_shorthand: f.is_shorthand,
1003         }
1004     }
1005
1006     fn lower_expr_yield(&mut self, span: Span, opt_expr: Option<&Expr>) -> hir::ExprKind {
1007         match self.generator_kind {
1008             Some(hir::GeneratorKind::Gen) => {},
1009             Some(hir::GeneratorKind::Async) => {
1010                 span_err!(
1011                     self.sess,
1012                     span,
1013                     E0727,
1014                     "`async` generators are not yet supported",
1015                 );
1016                 self.sess.abort_if_errors();
1017             },
1018             None => self.generator_kind = Some(hir::GeneratorKind::Gen),
1019         }
1020
1021         let expr = opt_expr
1022             .as_ref()
1023             .map(|x| self.lower_expr(x))
1024             .unwrap_or_else(|| self.expr_unit(span));
1025
1026         hir::ExprKind::Yield(P(expr), hir::YieldSource::Yield)
1027     }
1028
1029     /// Desugar `ExprForLoop` from: `[opt_ident]: for <pat> in <head> <body>` into:
1030     /// ```rust
1031     /// {
1032     ///     let result = match ::std::iter::IntoIterator::into_iter(<head>) {
1033     ///         mut iter => {
1034     ///             [opt_ident]: loop {
1035     ///                 let mut __next;
1036     ///                 match ::std::iter::Iterator::next(&mut iter) {
1037     ///                     ::std::option::Option::Some(val) => __next = val,
1038     ///                     ::std::option::Option::None => break
1039     ///                 };
1040     ///                 let <pat> = __next;
1041     ///                 StmtKind::Expr(<body>);
1042     ///             }
1043     ///         }
1044     ///     };
1045     ///     result
1046     /// }
1047     /// ```
1048     fn lower_expr_for(
1049         &mut self,
1050         e: &Expr,
1051         pat: &Pat,
1052         head: &Expr,
1053         body: &Block,
1054         opt_label: Option<Label>,
1055     ) -> hir::Expr {
1056         // expand <head>
1057         let mut head = self.lower_expr(head);
1058         let head_sp = head.span;
1059         let desugared_span = self.mark_span_with_reason(
1060             DesugaringKind::ForLoop,
1061             head_sp,
1062             None,
1063         );
1064         head.span = desugared_span;
1065
1066         let iter = Ident::with_dummy_span(sym::iter);
1067
1068         let next_ident = Ident::with_dummy_span(sym::__next);
1069         let (next_pat, next_pat_hid) = self.pat_ident_binding_mode(
1070             desugared_span,
1071             next_ident,
1072             hir::BindingAnnotation::Mutable,
1073         );
1074
1075         // `::std::option::Option::Some(val) => __next = val`
1076         let pat_arm = {
1077             let val_ident = Ident::with_dummy_span(sym::val);
1078             let (val_pat, val_pat_hid) = self.pat_ident(pat.span, val_ident);
1079             let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat_hid));
1080             let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat_hid));
1081             let assign = P(self.expr(
1082                 pat.span,
1083                 hir::ExprKind::Assign(next_expr, val_expr),
1084                 ThinVec::new(),
1085             ));
1086             let some_pat = self.pat_some(pat.span, val_pat);
1087             self.arm(hir_vec![some_pat], assign)
1088         };
1089
1090         // `::std::option::Option::None => break`
1091         let break_arm = {
1092             let break_expr =
1093                 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
1094             let pat = self.pat_none(e.span);
1095             self.arm(hir_vec![pat], break_expr)
1096         };
1097
1098         // `mut iter`
1099         let (iter_pat, iter_pat_nid) = self.pat_ident_binding_mode(
1100             desugared_span,
1101             iter,
1102             hir::BindingAnnotation::Mutable
1103         );
1104
1105         // `match ::std::iter::Iterator::next(&mut iter) { ... }`
1106         let match_expr = {
1107             let iter = P(self.expr_ident(head_sp, iter, iter_pat_nid));
1108             let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
1109             let next_path = &[sym::iter, sym::Iterator, sym::next];
1110             let next_expr = P(self.expr_call_std_path(
1111                 head_sp,
1112                 next_path,
1113                 hir_vec![ref_mut_iter],
1114             ));
1115             let arms = hir_vec![pat_arm, break_arm];
1116
1117             self.expr_match(head_sp, next_expr, arms, hir::MatchSource::ForLoopDesugar)
1118         };
1119         let match_stmt = self.stmt_expr(head_sp, match_expr);
1120
1121         let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat_hid));
1122
1123         // `let mut __next`
1124         let next_let = self.stmt_let_pat(
1125             ThinVec::new(),
1126             desugared_span,
1127             None,
1128             next_pat,
1129             hir::LocalSource::ForLoopDesugar,
1130         );
1131
1132         // `let <pat> = __next`
1133         let pat = self.lower_pat(pat);
1134         let pat_let = self.stmt_let_pat(
1135             ThinVec::new(),
1136             head_sp,
1137             Some(next_expr),
1138             pat,
1139             hir::LocalSource::ForLoopDesugar,
1140         );
1141
1142         let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
1143         let body_expr = self.expr_block(body_block, ThinVec::new());
1144         let body_stmt = self.stmt_expr(body.span, body_expr);
1145
1146         let loop_block = P(self.block_all(
1147             e.span,
1148             hir_vec![next_let, match_stmt, pat_let, body_stmt],
1149             None,
1150         ));
1151
1152         // `[opt_ident]: loop { ... }`
1153         let loop_expr = hir::ExprKind::Loop(
1154             loop_block,
1155             self.lower_label(opt_label),
1156             hir::LoopSource::ForLoop,
1157         );
1158         let loop_expr = P(hir::Expr {
1159             hir_id: self.lower_node_id(e.id),
1160             node: loop_expr,
1161             span: e.span,
1162             attrs: ThinVec::new(),
1163         });
1164
1165         // `mut iter => { ... }`
1166         let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
1167
1168         // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
1169         let into_iter_expr = {
1170             let into_iter_path =
1171                 &[sym::iter, sym::IntoIterator, sym::into_iter];
1172             P(self.expr_call_std_path(
1173                 head_sp,
1174                 into_iter_path,
1175                 hir_vec![head],
1176             ))
1177         };
1178
1179         let match_expr = P(self.expr_match(
1180             head_sp,
1181             into_iter_expr,
1182             hir_vec![iter_arm],
1183             hir::MatchSource::ForLoopDesugar,
1184         ));
1185
1186         // This is effectively `{ let _result = ...; _result }`.
1187         // The construct was introduced in #21984 and is necessary to make sure that
1188         // temporaries in the `head` expression are dropped and do not leak to the
1189         // surrounding scope of the `match` since the `match` is not a terminating scope.
1190         //
1191         // Also, add the attributes to the outer returned expr node.
1192         self.expr_drop_temps(head_sp, match_expr, e.attrs.clone())
1193     }
1194
1195     /// Desugar `ExprKind::Try` from: `<expr>?` into:
1196     /// ```rust
1197     /// match Try::into_result(<expr>) {
1198     ///     Ok(val) => #[allow(unreachable_code)] val,
1199     ///     Err(err) => #[allow(unreachable_code)]
1200     ///                 // If there is an enclosing `try {...}`:
1201     ///                 break 'catch_target Try::from_error(From::from(err)),
1202     ///                 // Otherwise:
1203     ///                 return Try::from_error(From::from(err)),
1204     /// }
1205     /// ```
1206     fn lower_expr_try(&mut self, span: Span, sub_expr: &Expr) -> hir::ExprKind {
1207         let unstable_span = self.mark_span_with_reason(
1208             DesugaringKind::QuestionMark,
1209             span,
1210             self.allow_try_trait.clone(),
1211         );
1212         let try_span = self.sess.source_map().end_point(span);
1213         let try_span = self.mark_span_with_reason(
1214             DesugaringKind::QuestionMark,
1215             try_span,
1216             self.allow_try_trait.clone(),
1217         );
1218
1219         // `Try::into_result(<expr>)`
1220         let scrutinee = {
1221             // expand <expr>
1222             let sub_expr = self.lower_expr(sub_expr);
1223
1224             let path = &[sym::ops, sym::Try, sym::into_result];
1225             P(self.expr_call_std_path(unstable_span, path, hir_vec![sub_expr]))
1226         };
1227
1228         // `#[allow(unreachable_code)]`
1229         let attr = {
1230             // `allow(unreachable_code)`
1231             let allow = {
1232                 let allow_ident = Ident::new(sym::allow, span);
1233                 let uc_ident = Ident::new(sym::unreachable_code, span);
1234                 let uc_nested = attr::mk_nested_word_item(uc_ident);
1235                 attr::mk_list_item(allow_ident, vec![uc_nested])
1236             };
1237             attr::mk_attr_outer(allow)
1238         };
1239         let attrs = vec![attr];
1240
1241         // `Ok(val) => #[allow(unreachable_code)] val,`
1242         let ok_arm = {
1243             let val_ident = Ident::with_dummy_span(sym::val);
1244             let (val_pat, val_pat_nid) = self.pat_ident(span, val_ident);
1245             let val_expr = P(self.expr_ident_with_attrs(
1246                 span,
1247                 val_ident,
1248                 val_pat_nid,
1249                 ThinVec::from(attrs.clone()),
1250             ));
1251             let ok_pat = self.pat_ok(span, val_pat);
1252             self.arm(hir_vec![ok_pat], val_expr)
1253         };
1254
1255         // `Err(err) => #[allow(unreachable_code)]
1256         //              return Try::from_error(From::from(err)),`
1257         let err_arm = {
1258             let err_ident = Ident::with_dummy_span(sym::err);
1259             let (err_local, err_local_nid) = self.pat_ident(try_span, err_ident);
1260             let from_expr = {
1261                 let from_path = &[sym::convert, sym::From, sym::from];
1262                 let err_expr = self.expr_ident(try_span, err_ident, err_local_nid);
1263                 self.expr_call_std_path(try_span, from_path, hir_vec![err_expr])
1264             };
1265             let from_err_expr =
1266                 self.wrap_in_try_constructor(sym::from_error, from_expr, unstable_span);
1267             let thin_attrs = ThinVec::from(attrs);
1268             let catch_scope = self.catch_scopes.last().map(|x| *x);
1269             let ret_expr = if let Some(catch_node) = catch_scope {
1270                 let target_id = Ok(self.lower_node_id(catch_node));
1271                 P(self.expr(
1272                     try_span,
1273                     hir::ExprKind::Break(
1274                         hir::Destination {
1275                             label: None,
1276                             target_id,
1277                         },
1278                         Some(from_err_expr),
1279                     ),
1280                     thin_attrs,
1281                 ))
1282             } else {
1283                 P(self.expr(try_span, hir::ExprKind::Ret(Some(from_err_expr)), thin_attrs))
1284             };
1285
1286             let err_pat = self.pat_err(try_span, err_local);
1287             self.arm(hir_vec![err_pat], ret_expr)
1288         };
1289
1290         hir::ExprKind::Match(
1291             scrutinee,
1292             hir_vec![err_arm, ok_arm],
1293             hir::MatchSource::TryDesugar,
1294         )
1295     }
1296
1297     // =========================================================================
1298     // Helper methods for building HIR.
1299     // =========================================================================
1300
1301     /// Constructs a `true` or `false` literal expression.
1302     pub(super) fn expr_bool(&mut self, span: Span, val: bool) -> hir::Expr {
1303         let lit = Spanned { span, node: LitKind::Bool(val) };
1304         self.expr(span, hir::ExprKind::Lit(lit), ThinVec::new())
1305     }
1306
1307     /// Wrap the given `expr` in a terminating scope using `hir::ExprKind::DropTemps`.
1308     ///
1309     /// In terms of drop order, it has the same effect as wrapping `expr` in
1310     /// `{ let _t = $expr; _t }` but should provide better compile-time performance.
1311     ///
1312     /// The drop order can be important in e.g. `if expr { .. }`.
1313     pub(super) fn expr_drop_temps(
1314         &mut self,
1315         span: Span,
1316         expr: P<hir::Expr>,
1317         attrs: ThinVec<Attribute>
1318     ) -> hir::Expr {
1319         self.expr(span, hir::ExprKind::DropTemps(expr), attrs)
1320     }
1321
1322     fn expr_match(
1323         &mut self,
1324         span: Span,
1325         arg: P<hir::Expr>,
1326         arms: hir::HirVec<hir::Arm>,
1327         source: hir::MatchSource,
1328     ) -> hir::Expr {
1329         self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
1330     }
1331
1332     fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
1333         let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
1334         P(self.expr(span, expr_break, attrs))
1335     }
1336
1337     fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
1338         self.expr(span, hir::ExprKind::AddrOf(hir::MutMutable, e), ThinVec::new())
1339     }
1340
1341     fn expr_unit(&mut self, sp: Span) -> hir::Expr {
1342         self.expr_tuple(sp, hir_vec![])
1343     }
1344
1345     fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> hir::Expr {
1346         self.expr(sp, hir::ExprKind::Tup(exprs), ThinVec::new())
1347     }
1348
1349     fn expr_call(
1350         &mut self,
1351         span: Span,
1352         e: P<hir::Expr>,
1353         args: hir::HirVec<hir::Expr>,
1354     ) -> hir::Expr {
1355         self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
1356     }
1357
1358     // Note: associated functions must use `expr_call_std_path`.
1359     fn expr_call_std_path(
1360         &mut self,
1361         span: Span,
1362         path_components: &[Symbol],
1363         args: hir::HirVec<hir::Expr>,
1364     ) -> hir::Expr {
1365         let path = P(self.expr_std_path(span, path_components, None, ThinVec::new()));
1366         self.expr_call(span, path, args)
1367     }
1368
1369     // Create an expression calling an associated function of an std type.
1370     //
1371     // Associated functions cannot be resolved through the normal `std_path` function,
1372     // as they are resolved differently and so cannot use `expr_call_std_path`.
1373     //
1374     // This function accepts the path component (`ty_path_components`) separately from
1375     // the name of the associated function (`assoc_fn_name`) in order to facilitate
1376     // separate resolution of the type and creation of a path referring to its associated
1377     // function.
1378     fn expr_call_std_assoc_fn(
1379         &mut self,
1380         ty_path_id: hir::HirId,
1381         span: Span,
1382         ty_path_components: &[Symbol],
1383         assoc_fn_name: &str,
1384         args: hir::HirVec<hir::Expr>,
1385     ) -> hir::ExprKind {
1386         let ty_path = P(self.std_path(span, ty_path_components, None, false));
1387         let ty = P(self.ty_path(ty_path_id, span, hir::QPath::Resolved(None, ty_path)));
1388         let fn_seg = P(hir::PathSegment::from_ident(Ident::from_str(assoc_fn_name)));
1389         let fn_path = hir::QPath::TypeRelative(ty, fn_seg);
1390         let fn_expr = P(self.expr(span, hir::ExprKind::Path(fn_path), ThinVec::new()));
1391         hir::ExprKind::Call(fn_expr, args)
1392     }
1393
1394     fn expr_std_path(
1395         &mut self,
1396         span: Span,
1397         components: &[Symbol],
1398         params: Option<P<hir::GenericArgs>>,
1399         attrs: ThinVec<Attribute>,
1400     ) -> hir::Expr {
1401         let path = self.std_path(span, components, params, true);
1402         self.expr(
1403             span,
1404             hir::ExprKind::Path(hir::QPath::Resolved(None, P(path))),
1405             attrs,
1406         )
1407     }
1408
1409     pub(super) fn expr_ident(&mut self, sp: Span, ident: Ident, binding: hir::HirId) -> hir::Expr {
1410         self.expr_ident_with_attrs(sp, ident, binding, ThinVec::new())
1411     }
1412
1413     fn expr_ident_with_attrs(
1414         &mut self,
1415         span: Span,
1416         ident: Ident,
1417         binding: hir::HirId,
1418         attrs: ThinVec<Attribute>,
1419     ) -> hir::Expr {
1420         let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
1421             None,
1422             P(hir::Path {
1423                 span,
1424                 res: Res::Local(binding),
1425                 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1426             }),
1427         ));
1428
1429         self.expr(span, expr_path, attrs)
1430     }
1431
1432     fn expr_unsafe(&mut self, expr: P<hir::Expr>) -> hir::Expr {
1433         let hir_id = self.next_id();
1434         let span = expr.span;
1435         self.expr(
1436             span,
1437             hir::ExprKind::Block(P(hir::Block {
1438                 stmts: hir_vec![],
1439                 expr: Some(expr),
1440                 hir_id,
1441                 rules: hir::UnsafeBlock(hir::CompilerGenerated),
1442                 span,
1443                 targeted_by_break: false,
1444             }), None),
1445             ThinVec::new(),
1446         )
1447     }
1448
1449     fn expr_block_empty(&mut self, span: Span) -> hir::Expr {
1450         let blk = self.block_all(span, hir_vec![], None);
1451         self.expr_block(P(blk), ThinVec::new())
1452     }
1453
1454     pub(super) fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
1455         self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
1456     }
1457
1458     pub(super) fn expr(
1459         &mut self,
1460         span: Span,
1461         node: hir::ExprKind,
1462         attrs: ThinVec<Attribute>
1463     ) -> hir::Expr {
1464         hir::Expr {
1465             hir_id: self.next_id(),
1466             node,
1467             span,
1468             attrs,
1469         }
1470     }
1471
1472     fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
1473         hir::Field {
1474             hir_id: self.next_id(),
1475             ident,
1476             span,
1477             expr,
1478             is_shorthand: false,
1479         }
1480     }
1481
1482     /// HACK(or_patterns; Centril | dlrobertson): For now we don't push down top level or-patterns
1483     /// `p | q` into `hir::PatKind::Or(...)` as post-lowering bits of the compiler are not ready
1484     /// to deal with it. This should by fixed by pushing it down to HIR and then HAIR.
1485     fn arm(&mut self, pats: HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
1486         hir::Arm {
1487             hir_id: self.next_id(),
1488             attrs: hir_vec![],
1489             pats,
1490             guard: None,
1491             span: expr.span,
1492             body: expr,
1493         }
1494     }
1495 }