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