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