]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast_lowering/src/expr.rs
Rollup merge of #86566 - fee1-dead:mir-pretty-print, r=oli-obk
[rust.git] / compiler / rustc_ast_lowering / src / expr.rs
1 use super::{ImplTraitContext, LoweringContext, ParamMode, ParenthesizedGenericArgs};
2
3 use rustc_ast::attr;
4 use rustc_ast::ptr::P as AstP;
5 use rustc_ast::*;
6 use rustc_data_structures::stack::ensure_sufficient_stack;
7 use rustc_data_structures::thin_vec::ThinVec;
8 use rustc_errors::struct_span_err;
9 use rustc_hir as hir;
10 use rustc_hir::def::Res;
11 use rustc_hir::definitions::DefPathData;
12 use rustc_session::parse::feature_err;
13 use rustc_span::hygiene::ExpnId;
14 use rustc_span::source_map::{respan, DesugaringKind, Span, Spanned};
15 use rustc_span::symbol::{sym, Ident, Symbol};
16 use rustc_span::{hygiene::ForLoopLoc, DUMMY_SP};
17
18 impl<'hir> LoweringContext<'_, 'hir> {
19     fn lower_exprs(&mut self, exprs: &[AstP<Expr>]) -> &'hir [hir::Expr<'hir>] {
20         self.arena.alloc_from_iter(exprs.iter().map(|x| self.lower_expr_mut(x)))
21     }
22
23     pub(super) fn lower_expr(&mut self, e: &Expr) -> &'hir hir::Expr<'hir> {
24         self.arena.alloc(self.lower_expr_mut(e))
25     }
26
27     pub(super) fn lower_expr_mut(&mut self, e: &Expr) -> hir::Expr<'hir> {
28         ensure_sufficient_stack(|| {
29             let kind = match e.kind {
30                 ExprKind::Box(ref inner) => hir::ExprKind::Box(self.lower_expr(inner)),
31                 ExprKind::Array(ref exprs) => hir::ExprKind::Array(self.lower_exprs(exprs)),
32                 ExprKind::ConstBlock(ref anon_const) => {
33                     let anon_const = self.lower_anon_const(anon_const);
34                     hir::ExprKind::ConstBlock(anon_const)
35                 }
36                 ExprKind::Repeat(ref expr, ref count) => {
37                     let expr = self.lower_expr(expr);
38                     let count = self.lower_anon_const(count);
39                     hir::ExprKind::Repeat(expr, count)
40                 }
41                 ExprKind::Tup(ref elts) => hir::ExprKind::Tup(self.lower_exprs(elts)),
42                 ExprKind::Call(ref f, ref args) => {
43                     if let Some(legacy_args) = self.resolver.legacy_const_generic_args(f) {
44                         self.lower_legacy_const_generics((**f).clone(), args.clone(), &legacy_args)
45                     } else {
46                         let f = self.lower_expr(f);
47                         hir::ExprKind::Call(f, self.lower_exprs(args))
48                     }
49                 }
50                 ExprKind::MethodCall(ref seg, ref args, span) => {
51                     let hir_seg = self.arena.alloc(self.lower_path_segment(
52                         e.span,
53                         seg,
54                         ParamMode::Optional,
55                         0,
56                         ParenthesizedGenericArgs::Err,
57                         ImplTraitContext::disallowed(),
58                         None,
59                     ));
60                     let args = self.lower_exprs(args);
61                     hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args, span)
62                 }
63                 ExprKind::Binary(binop, ref lhs, ref rhs) => {
64                     let binop = self.lower_binop(binop);
65                     let lhs = self.lower_expr(lhs);
66                     let rhs = self.lower_expr(rhs);
67                     hir::ExprKind::Binary(binop, lhs, rhs)
68                 }
69                 ExprKind::Unary(op, ref ohs) => {
70                     let op = self.lower_unop(op);
71                     let ohs = self.lower_expr(ohs);
72                     hir::ExprKind::Unary(op, ohs)
73                 }
74                 ExprKind::Lit(ref l) => hir::ExprKind::Lit(respan(l.span, l.kind.clone())),
75                 ExprKind::Cast(ref expr, ref ty) => {
76                     let expr = self.lower_expr(expr);
77                     let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
78                     hir::ExprKind::Cast(expr, ty)
79                 }
80                 ExprKind::Type(ref expr, ref ty) => {
81                     let expr = self.lower_expr(expr);
82                     let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
83                     hir::ExprKind::Type(expr, ty)
84                 }
85                 ExprKind::AddrOf(k, m, ref ohs) => {
86                     let ohs = self.lower_expr(ohs);
87                     hir::ExprKind::AddrOf(k, m, ohs)
88                 }
89                 ExprKind::Let(ref pat, ref scrutinee) => {
90                     self.lower_expr_let(e.span, pat, scrutinee)
91                 }
92                 ExprKind::If(ref cond, ref then, ref else_opt) => match cond.kind {
93                     ExprKind::Let(ref pat, ref scrutinee) => {
94                         self.lower_expr_if_let(e.span, pat, scrutinee, then, else_opt.as_deref())
95                     }
96                     ExprKind::Paren(ref paren) => match paren.peel_parens().kind {
97                         ExprKind::Let(ref pat, ref scrutinee) => {
98                             // A user has written `if (let Some(x) = foo) {`, we want to avoid
99                             // confusing them with mentions of nightly features.
100                             // If this logic is changed, you will also likely need to touch
101                             // `unused::UnusedParens::check_expr`.
102                             self.if_let_expr_with_parens(cond, &paren.peel_parens());
103                             self.lower_expr_if_let(
104                                 e.span,
105                                 pat,
106                                 scrutinee,
107                                 then,
108                                 else_opt.as_deref(),
109                             )
110                         }
111                         _ => self.lower_expr_if(cond, then, else_opt.as_deref()),
112                     },
113                     _ => self.lower_expr_if(cond, then, else_opt.as_deref()),
114                 },
115                 ExprKind::While(ref cond, ref body, opt_label) => self
116                     .with_loop_scope(e.id, |this| {
117                         this.lower_expr_while_in_loop_scope(e.span, cond, body, opt_label)
118                     }),
119                 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
120                     hir::ExprKind::Loop(
121                         this.lower_block(body, false),
122                         opt_label,
123                         hir::LoopSource::Loop,
124                         DUMMY_SP,
125                     )
126                 }),
127                 ExprKind::TryBlock(ref body) => self.lower_expr_try_block(body),
128                 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
129                     self.lower_expr(expr),
130                     self.arena.alloc_from_iter(arms.iter().map(|x| self.lower_arm(x))),
131                     hir::MatchSource::Normal,
132                 ),
133                 ExprKind::Async(capture_clause, closure_node_id, ref block) => self
134                     .make_async_expr(
135                         capture_clause,
136                         closure_node_id,
137                         None,
138                         block.span,
139                         hir::AsyncGeneratorKind::Block,
140                         |this| this.with_new_scopes(|this| this.lower_block_expr(block)),
141                     ),
142                 ExprKind::Await(ref expr) => self.lower_expr_await(e.span, expr),
143                 ExprKind::Closure(
144                     capture_clause,
145                     asyncness,
146                     movability,
147                     ref decl,
148                     ref body,
149                     fn_decl_span,
150                 ) => {
151                     if let Async::Yes { closure_id, .. } = asyncness {
152                         self.lower_expr_async_closure(
153                             capture_clause,
154                             closure_id,
155                             decl,
156                             body,
157                             fn_decl_span,
158                         )
159                     } else {
160                         self.lower_expr_closure(
161                             capture_clause,
162                             movability,
163                             decl,
164                             body,
165                             fn_decl_span,
166                         )
167                     }
168                 }
169                 ExprKind::Block(ref blk, opt_label) => {
170                     hir::ExprKind::Block(self.lower_block(blk, opt_label.is_some()), opt_label)
171                 }
172                 ExprKind::Assign(ref el, ref er, span) => {
173                     self.lower_expr_assign(el, er, span, e.span)
174                 }
175                 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
176                     self.lower_binop(op),
177                     self.lower_expr(el),
178                     self.lower_expr(er),
179                 ),
180                 ExprKind::Field(ref el, ident) => hir::ExprKind::Field(self.lower_expr(el), ident),
181                 ExprKind::Index(ref el, ref er) => {
182                     hir::ExprKind::Index(self.lower_expr(el), self.lower_expr(er))
183                 }
184                 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
185                     self.lower_expr_range_closed(e.span, e1, e2)
186                 }
187                 ExprKind::Range(ref e1, ref e2, lims) => {
188                     self.lower_expr_range(e.span, e1.as_deref(), e2.as_deref(), lims)
189                 }
190                 ExprKind::Underscore => {
191                     self.sess
192                         .struct_span_err(
193                             e.span,
194                             "in expressions, `_` can only be used on the left-hand side of an assignment",
195                         )
196                         .span_label(e.span, "`_` not allowed here")
197                         .emit();
198                     hir::ExprKind::Err
199                 }
200                 ExprKind::Path(ref qself, ref path) => {
201                     let qpath = self.lower_qpath(
202                         e.id,
203                         qself,
204                         path,
205                         ParamMode::Optional,
206                         ImplTraitContext::disallowed(),
207                     );
208                     hir::ExprKind::Path(qpath)
209                 }
210                 ExprKind::Break(opt_label, ref opt_expr) => {
211                     let opt_expr = opt_expr.as_ref().map(|x| self.lower_expr(x));
212                     hir::ExprKind::Break(self.lower_jump_destination(e.id, opt_label), opt_expr)
213                 }
214                 ExprKind::Continue(opt_label) => {
215                     hir::ExprKind::Continue(self.lower_jump_destination(e.id, opt_label))
216                 }
217                 ExprKind::Ret(ref e) => {
218                     let e = e.as_ref().map(|x| self.lower_expr(x));
219                     hir::ExprKind::Ret(e)
220                 }
221                 ExprKind::InlineAsm(ref asm) => {
222                     hir::ExprKind::InlineAsm(self.lower_inline_asm(e.span, asm))
223                 }
224                 ExprKind::LlvmInlineAsm(ref asm) => self.lower_expr_llvm_asm(asm),
225                 ExprKind::Struct(ref se) => {
226                     let rest = match &se.rest {
227                         StructRest::Base(e) => Some(self.lower_expr(e)),
228                         StructRest::Rest(sp) => {
229                             self.sess
230                                 .struct_span_err(*sp, "base expression required after `..`")
231                                 .span_label(*sp, "add a base expression here")
232                                 .emit();
233                             Some(&*self.arena.alloc(self.expr_err(*sp)))
234                         }
235                         StructRest::None => None,
236                     };
237                     hir::ExprKind::Struct(
238                         self.arena.alloc(self.lower_qpath(
239                             e.id,
240                             &se.qself,
241                             &se.path,
242                             ParamMode::Optional,
243                             ImplTraitContext::disallowed(),
244                         )),
245                         self.arena
246                             .alloc_from_iter(se.fields.iter().map(|x| self.lower_expr_field(x))),
247                         rest,
248                     )
249                 }
250                 ExprKind::Yield(ref opt_expr) => self.lower_expr_yield(e.span, opt_expr.as_deref()),
251                 ExprKind::Err => hir::ExprKind::Err,
252                 ExprKind::Try(ref sub_expr) => self.lower_expr_try(e.span, sub_expr),
253                 ExprKind::Paren(ref ex) => {
254                     let mut ex = self.lower_expr_mut(ex);
255                     // Include parens in span, but only if it is a super-span.
256                     if e.span.contains(ex.span) {
257                         ex.span = e.span;
258                     }
259                     // Merge attributes into the inner expression.
260                     if !e.attrs.is_empty() {
261                         let old_attrs = self.attrs.get(&ex.hir_id).map(|la| *la).unwrap_or(&[]);
262                         self.attrs.insert(
263                             ex.hir_id,
264                             &*self.arena.alloc_from_iter(
265                                 e.attrs
266                                     .iter()
267                                     .map(|a| self.lower_attr(a))
268                                     .chain(old_attrs.iter().cloned()),
269                             ),
270                         );
271                     }
272                     return ex;
273                 }
274
275                 // Desugar `ExprForLoop`
276                 // from: `[opt_ident]: for <pat> in <head> <body>`
277                 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
278                     return self.lower_expr_for(e, pat, head, body, opt_label);
279                 }
280                 ExprKind::MacCall(_) => panic!("{:?} shouldn't exist here", e.span),
281             };
282
283             let hir_id = self.lower_node_id(e.id);
284             self.lower_attrs(hir_id, &e.attrs);
285             hir::Expr { hir_id, kind, span: e.span }
286         })
287     }
288
289     fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
290         match u {
291             UnOp::Deref => hir::UnOp::Deref,
292             UnOp::Not => hir::UnOp::Not,
293             UnOp::Neg => hir::UnOp::Neg,
294         }
295     }
296
297     fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
298         Spanned {
299             node: match b.node {
300                 BinOpKind::Add => hir::BinOpKind::Add,
301                 BinOpKind::Sub => hir::BinOpKind::Sub,
302                 BinOpKind::Mul => hir::BinOpKind::Mul,
303                 BinOpKind::Div => hir::BinOpKind::Div,
304                 BinOpKind::Rem => hir::BinOpKind::Rem,
305                 BinOpKind::And => hir::BinOpKind::And,
306                 BinOpKind::Or => hir::BinOpKind::Or,
307                 BinOpKind::BitXor => hir::BinOpKind::BitXor,
308                 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
309                 BinOpKind::BitOr => hir::BinOpKind::BitOr,
310                 BinOpKind::Shl => hir::BinOpKind::Shl,
311                 BinOpKind::Shr => hir::BinOpKind::Shr,
312                 BinOpKind::Eq => hir::BinOpKind::Eq,
313                 BinOpKind::Lt => hir::BinOpKind::Lt,
314                 BinOpKind::Le => hir::BinOpKind::Le,
315                 BinOpKind::Ne => hir::BinOpKind::Ne,
316                 BinOpKind::Ge => hir::BinOpKind::Ge,
317                 BinOpKind::Gt => hir::BinOpKind::Gt,
318             },
319             span: b.span,
320         }
321     }
322
323     fn lower_legacy_const_generics(
324         &mut self,
325         mut f: Expr,
326         args: Vec<AstP<Expr>>,
327         legacy_args_idx: &[usize],
328     ) -> hir::ExprKind<'hir> {
329         let path = match f.kind {
330             ExprKind::Path(None, ref mut path) => path,
331             _ => unreachable!(),
332         };
333
334         // Split the arguments into const generics and normal arguments
335         let mut real_args = vec![];
336         let mut generic_args = vec![];
337         for (idx, arg) in args.into_iter().enumerate() {
338             if legacy_args_idx.contains(&idx) {
339                 let parent_def_id = self.current_hir_id_owner.0;
340                 let node_id = self.resolver.next_node_id();
341
342                 // Add a definition for the in-band const def.
343                 self.resolver.create_def(
344                     parent_def_id,
345                     node_id,
346                     DefPathData::AnonConst,
347                     ExpnId::root(),
348                     arg.span,
349                 );
350
351                 let anon_const = AnonConst { id: node_id, value: arg };
352                 generic_args.push(AngleBracketedArg::Arg(GenericArg::Const(anon_const)));
353             } else {
354                 real_args.push(arg);
355             }
356         }
357
358         // Add generic args to the last element of the path.
359         let last_segment = path.segments.last_mut().unwrap();
360         assert!(last_segment.args.is_none());
361         last_segment.args = Some(AstP(GenericArgs::AngleBracketed(AngleBracketedArgs {
362             span: DUMMY_SP,
363             args: generic_args,
364         })));
365
366         // Now lower everything as normal.
367         let f = self.lower_expr(&f);
368         hir::ExprKind::Call(f, self.lower_exprs(&real_args))
369     }
370
371     fn if_let_expr_with_parens(&mut self, cond: &Expr, paren: &Expr) {
372         let start = cond.span.until(paren.span);
373         let end = paren.span.shrink_to_hi().until(cond.span.shrink_to_hi());
374         self.sess
375             .struct_span_err(
376                 vec![start, end],
377                 "invalid parentheses around `let` expression in `if let`",
378             )
379             .multipart_suggestion(
380                 "`if let` needs to be written without parentheses",
381                 vec![(start, String::new()), (end, String::new())],
382                 rustc_errors::Applicability::MachineApplicable,
383             )
384             .emit();
385         // Ideally, we'd remove the feature gating of a `let` expression since we are already
386         // complaining about it here, but `feature_gate::check_crate` has already run by now:
387         // self.sess.parse_sess.gated_spans.ungate_last(sym::let_chains, paren.span);
388     }
389
390     /// Emit an error and lower `ast::ExprKind::Let(pat, scrutinee)` into:
391     /// ```rust
392     /// match scrutinee { pats => true, _ => false }
393     /// ```
394     fn lower_expr_let(&mut self, span: Span, pat: &Pat, scrutinee: &Expr) -> hir::ExprKind<'hir> {
395         // If we got here, the `let` expression is not allowed.
396
397         if self.sess.opts.unstable_features.is_nightly_build() {
398             self.sess
399                 .struct_span_err(span, "`let` expressions are not supported here")
400                 .note(
401                     "only supported directly without parentheses in conditions of `if`- and \
402                      `while`-expressions, as well as in `let` chains within parentheses",
403                 )
404                 .emit();
405         } else {
406             self.sess
407                 .struct_span_err(span, "expected expression, found statement (`let`)")
408                 .note("variable declaration using `let` is a statement")
409                 .emit();
410         }
411
412         // For better recovery, we emit:
413         // ```
414         // match scrutinee { pat => true, _ => false }
415         // ```
416         // While this doesn't fully match the user's intent, it has key advantages:
417         // 1. We can avoid using `abort_if_errors`.
418         // 2. We can typeck both `pat` and `scrutinee`.
419         // 3. `pat` is allowed to be refutable.
420         // 4. The return type of the block is `bool` which seems like what the user wanted.
421         let scrutinee = self.lower_expr(scrutinee);
422         let then_arm = {
423             let pat = self.lower_pat(pat);
424             let expr = self.expr_bool(span, true);
425             self.arm(pat, expr)
426         };
427         let else_arm = {
428             let pat = self.pat_wild(span);
429             let expr = self.expr_bool(span, false);
430             self.arm(pat, expr)
431         };
432         hir::ExprKind::Match(
433             scrutinee,
434             arena_vec![self; then_arm, else_arm],
435             hir::MatchSource::Normal,
436         )
437     }
438
439     fn lower_expr_if(
440         &mut self,
441         cond: &Expr,
442         then: &Block,
443         else_opt: Option<&Expr>,
444     ) -> hir::ExprKind<'hir> {
445         macro_rules! make_if {
446             ($opt:expr) => {{
447                 let cond = self.lower_expr(cond);
448                 let then_expr = self.lower_block_expr(then);
449                 hir::ExprKind::If(cond, self.arena.alloc(then_expr), $opt)
450             }};
451         }
452         if let Some(rslt) = else_opt {
453             make_if!(Some(self.lower_expr(rslt)))
454         } else {
455             make_if!(None)
456         }
457     }
458
459     fn lower_expr_if_let(
460         &mut self,
461         span: Span,
462         pat: &Pat,
463         scrutinee: &Expr,
464         then: &Block,
465         else_opt: Option<&Expr>,
466     ) -> hir::ExprKind<'hir> {
467         // FIXME(#53667): handle lowering of && and parens.
468
469         // `_ => else_block` where `else_block` is `{}` if there's `None`:
470         let else_pat = self.pat_wild(span);
471         let (else_expr, contains_else_clause) = match else_opt {
472             None => (self.expr_block_empty(span.shrink_to_hi()), false),
473             Some(els) => (self.lower_expr(els), true),
474         };
475         let else_arm = self.arm(else_pat, else_expr);
476
477         // Handle then + scrutinee:
478         let scrutinee = self.lower_expr(scrutinee);
479         let then_pat = self.lower_pat(pat);
480
481         let then_expr = self.lower_block_expr(then);
482         let then_arm = self.arm(then_pat, self.arena.alloc(then_expr));
483
484         let desugar = hir::MatchSource::IfLetDesugar { contains_else_clause };
485         hir::ExprKind::Match(scrutinee, arena_vec![self; then_arm, else_arm], desugar)
486     }
487
488     fn lower_expr_while_in_loop_scope(
489         &mut self,
490         span: Span,
491         cond: &Expr,
492         body: &Block,
493         opt_label: Option<Label>,
494     ) -> hir::ExprKind<'hir> {
495         // FIXME(#53667): handle lowering of && and parens.
496
497         // Note that the block AND the condition are evaluated in the loop scope.
498         // This is done to allow `break` from inside the condition of the loop.
499
500         // `_ => break`:
501         let else_arm = {
502             let else_pat = self.pat_wild(span);
503             let else_expr = self.expr_break(span, ThinVec::new());
504             self.arm(else_pat, else_expr)
505         };
506
507         // Handle then + scrutinee:
508         let (then_pat, scrutinee, desugar, source) = match cond.kind {
509             ExprKind::Let(ref pat, ref scrutinee) => {
510                 // to:
511                 //
512                 //   [opt_ident]: loop {
513                 //     match <sub_expr> {
514                 //       <pat> => <body>,
515                 //       _ => break
516                 //     }
517                 //   }
518                 let scrutinee = self.with_loop_condition_scope(|t| t.lower_expr(scrutinee));
519                 let pat = self.lower_pat(pat);
520                 (pat, scrutinee, hir::MatchSource::WhileLetDesugar, hir::LoopSource::WhileLet)
521             }
522             _ => {
523                 // We desugar: `'label: while $cond $body` into:
524                 //
525                 // ```
526                 // 'label: loop {
527                 //     match drop-temps { $cond } {
528                 //         true => $body,
529                 //         _ => break,
530                 //     }
531                 // }
532                 // ```
533
534                 // Lower condition:
535                 let cond = self.with_loop_condition_scope(|this| this.lower_expr(cond));
536                 let span_block =
537                     self.mark_span_with_reason(DesugaringKind::CondTemporary, cond.span, None);
538                 // Wrap in a construct equivalent to `{ let _t = $cond; _t }`
539                 // to preserve drop semantics since `while cond { ... }` does not
540                 // let temporaries live outside of `cond`.
541                 let cond = self.expr_drop_temps(span_block, cond, ThinVec::new());
542                 // `true => <then>`:
543                 let pat = self.pat_bool(span, true);
544                 (pat, cond, hir::MatchSource::WhileDesugar, hir::LoopSource::While)
545             }
546         };
547         let then_expr = self.lower_block_expr(body);
548         let then_arm = self.arm(then_pat, self.arena.alloc(then_expr));
549
550         // `match <scrutinee> { ... }`
551         let match_expr =
552             self.expr_match(span, scrutinee, arena_vec![self; then_arm, else_arm], desugar);
553
554         // `[opt_ident]: loop { ... }`
555         hir::ExprKind::Loop(
556             self.block_expr(self.arena.alloc(match_expr)),
557             opt_label,
558             source,
559             span.with_hi(cond.span.hi()),
560         )
561     }
562
563     /// Desugar `try { <stmts>; <expr> }` into `{ <stmts>; ::std::ops::Try::from_output(<expr>) }`,
564     /// `try { <stmts>; }` into `{ <stmts>; ::std::ops::Try::from_output(()) }`
565     /// and save the block id to use it as a break target for desugaring of the `?` operator.
566     fn lower_expr_try_block(&mut self, body: &Block) -> hir::ExprKind<'hir> {
567         self.with_catch_scope(body.id, |this| {
568             let mut block = this.lower_block_noalloc(body, true);
569
570             // Final expression of the block (if present) or `()` with span at the end of block
571             let (try_span, tail_expr) = if let Some(expr) = block.expr.take() {
572                 (
573                     this.mark_span_with_reason(
574                         DesugaringKind::TryBlock,
575                         expr.span,
576                         this.allow_try_trait.clone(),
577                     ),
578                     expr,
579                 )
580             } else {
581                 let try_span = this.mark_span_with_reason(
582                     DesugaringKind::TryBlock,
583                     this.sess.source_map().end_point(body.span),
584                     this.allow_try_trait.clone(),
585                 );
586
587                 (try_span, this.expr_unit(try_span))
588             };
589
590             let ok_wrapped_span =
591                 this.mark_span_with_reason(DesugaringKind::TryBlock, tail_expr.span, None);
592
593             // `::std::ops::Try::from_output($tail_expr)`
594             block.expr = Some(this.wrap_in_try_constructor(
595                 hir::LangItem::TryTraitFromOutput,
596                 try_span,
597                 tail_expr,
598                 ok_wrapped_span,
599             ));
600
601             hir::ExprKind::Block(this.arena.alloc(block), None)
602         })
603     }
604
605     fn wrap_in_try_constructor(
606         &mut self,
607         lang_item: hir::LangItem,
608         method_span: Span,
609         expr: &'hir hir::Expr<'hir>,
610         overall_span: Span,
611     ) -> &'hir hir::Expr<'hir> {
612         let constructor =
613             self.arena.alloc(self.expr_lang_item_path(method_span, lang_item, ThinVec::new()));
614         self.expr_call(overall_span, constructor, std::slice::from_ref(expr))
615     }
616
617     fn lower_arm(&mut self, arm: &Arm) -> hir::Arm<'hir> {
618         let pat = self.lower_pat(&arm.pat);
619         let guard = arm.guard.as_ref().map(|cond| {
620             if let ExprKind::Let(ref pat, ref scrutinee) = cond.kind {
621                 hir::Guard::IfLet(self.lower_pat(pat), self.lower_expr(scrutinee))
622             } else {
623                 hir::Guard::If(self.lower_expr(cond))
624             }
625         });
626         let hir_id = self.next_id();
627         self.lower_attrs(hir_id, &arm.attrs);
628         hir::Arm { hir_id, pat, guard, body: self.lower_expr(&arm.body), span: arm.span }
629     }
630
631     /// Lower an `async` construct to a generator that is then wrapped so it implements `Future`.
632     ///
633     /// This results in:
634     ///
635     /// ```text
636     /// std::future::from_generator(static move? |_task_context| -> <ret_ty> {
637     ///     <body>
638     /// })
639     /// ```
640     pub(super) fn make_async_expr(
641         &mut self,
642         capture_clause: CaptureBy,
643         closure_node_id: NodeId,
644         ret_ty: Option<AstP<Ty>>,
645         span: Span,
646         async_gen_kind: hir::AsyncGeneratorKind,
647         body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
648     ) -> hir::ExprKind<'hir> {
649         let output = match ret_ty {
650             Some(ty) => hir::FnRetTy::Return(self.lower_ty(&ty, ImplTraitContext::disallowed())),
651             None => hir::FnRetTy::DefaultReturn(span),
652         };
653
654         // Resume argument type. We let the compiler infer this to simplify the lowering. It is
655         // fully constrained by `future::from_generator`.
656         let input_ty = hir::Ty { hir_id: self.next_id(), kind: hir::TyKind::Infer, span };
657
658         // The closure/generator `FnDecl` takes a single (resume) argument of type `input_ty`.
659         let decl = self.arena.alloc(hir::FnDecl {
660             inputs: arena_vec![self; input_ty],
661             output,
662             c_variadic: false,
663             implicit_self: hir::ImplicitSelfKind::None,
664         });
665
666         // Lower the argument pattern/ident. The ident is used again in the `.await` lowering.
667         let (pat, task_context_hid) = self.pat_ident_binding_mode(
668             span,
669             Ident::with_dummy_span(sym::_task_context),
670             hir::BindingAnnotation::Mutable,
671         );
672         let param = hir::Param { hir_id: self.next_id(), pat, ty_span: span, span };
673         let params = arena_vec![self; param];
674
675         let body_id = self.lower_body(move |this| {
676             this.generator_kind = Some(hir::GeneratorKind::Async(async_gen_kind));
677
678             let old_ctx = this.task_context;
679             this.task_context = Some(task_context_hid);
680             let res = body(this);
681             this.task_context = old_ctx;
682             (params, res)
683         });
684
685         // `static |_task_context| -> <ret_ty> { body }`:
686         let generator_kind = hir::ExprKind::Closure(
687             capture_clause,
688             decl,
689             body_id,
690             span,
691             Some(hir::Movability::Static),
692         );
693         let generator =
694             hir::Expr { hir_id: self.lower_node_id(closure_node_id), kind: generator_kind, span };
695
696         // `future::from_generator`:
697         let unstable_span =
698             self.mark_span_with_reason(DesugaringKind::Async, span, self.allow_gen_future.clone());
699         let gen_future =
700             self.expr_lang_item_path(unstable_span, hir::LangItem::FromGenerator, ThinVec::new());
701
702         // `future::from_generator(generator)`:
703         hir::ExprKind::Call(self.arena.alloc(gen_future), arena_vec![self; generator])
704     }
705
706     /// Desugar `<expr>.await` into:
707     /// ```rust
708     /// match <expr> {
709     ///     mut pinned => loop {
710     ///         match unsafe { ::std::future::Future::poll(
711     ///             <::std::pin::Pin>::new_unchecked(&mut pinned),
712     ///             ::std::future::get_context(task_context),
713     ///         ) } {
714     ///             ::std::task::Poll::Ready(result) => break result,
715     ///             ::std::task::Poll::Pending => {}
716     ///         }
717     ///         task_context = yield ();
718     ///     }
719     /// }
720     /// ```
721     fn lower_expr_await(&mut self, await_span: Span, expr: &Expr) -> hir::ExprKind<'hir> {
722         match self.generator_kind {
723             Some(hir::GeneratorKind::Async(_)) => {}
724             Some(hir::GeneratorKind::Gen) | None => {
725                 let mut err = struct_span_err!(
726                     self.sess,
727                     await_span,
728                     E0728,
729                     "`await` is only allowed inside `async` functions and blocks"
730                 );
731                 err.span_label(await_span, "only allowed inside `async` functions and blocks");
732                 if let Some(item_sp) = self.current_item {
733                     err.span_label(item_sp, "this is not `async`");
734                 }
735                 err.emit();
736             }
737         }
738         let span = self.mark_span_with_reason(DesugaringKind::Await, await_span, None);
739         let gen_future_span = self.mark_span_with_reason(
740             DesugaringKind::Await,
741             await_span,
742             self.allow_gen_future.clone(),
743         );
744         let expr = self.lower_expr(expr);
745
746         let pinned_ident = Ident::with_dummy_span(sym::pinned);
747         let (pinned_pat, pinned_pat_hid) =
748             self.pat_ident_binding_mode(span, pinned_ident, hir::BindingAnnotation::Mutable);
749
750         let task_context_ident = Ident::with_dummy_span(sym::_task_context);
751
752         // unsafe {
753         //     ::std::future::Future::poll(
754         //         ::std::pin::Pin::new_unchecked(&mut pinned),
755         //         ::std::future::get_context(task_context),
756         //     )
757         // }
758         let poll_expr = {
759             let pinned = self.expr_ident(span, pinned_ident, pinned_pat_hid);
760             let ref_mut_pinned = self.expr_mut_addr_of(span, pinned);
761             let task_context = if let Some(task_context_hid) = self.task_context {
762                 self.expr_ident_mut(span, task_context_ident, task_context_hid)
763             } else {
764                 // Use of `await` outside of an async context, we cannot use `task_context` here.
765                 self.expr_err(span)
766             };
767             let new_unchecked = self.expr_call_lang_item_fn_mut(
768                 span,
769                 hir::LangItem::PinNewUnchecked,
770                 arena_vec![self; ref_mut_pinned],
771             );
772             let get_context = self.expr_call_lang_item_fn_mut(
773                 gen_future_span,
774                 hir::LangItem::GetContext,
775                 arena_vec![self; task_context],
776             );
777             let call = self.expr_call_lang_item_fn(
778                 span,
779                 hir::LangItem::FuturePoll,
780                 arena_vec![self; new_unchecked, get_context],
781             );
782             self.arena.alloc(self.expr_unsafe(call))
783         };
784
785         // `::std::task::Poll::Ready(result) => break result`
786         let loop_node_id = self.resolver.next_node_id();
787         let loop_hir_id = self.lower_node_id(loop_node_id);
788         let ready_arm = {
789             let x_ident = Ident::with_dummy_span(sym::result);
790             let (x_pat, x_pat_hid) = self.pat_ident(span, x_ident);
791             let x_expr = self.expr_ident(span, x_ident, x_pat_hid);
792             let ready_field = self.single_pat_field(span, x_pat);
793             let ready_pat = self.pat_lang_item_variant(span, hir::LangItem::PollReady, ready_field);
794             let break_x = self.with_loop_scope(loop_node_id, move |this| {
795                 let expr_break =
796                     hir::ExprKind::Break(this.lower_loop_destination(None), Some(x_expr));
797                 this.arena.alloc(this.expr(await_span, expr_break, ThinVec::new()))
798             });
799             self.arm(ready_pat, break_x)
800         };
801
802         // `::std::task::Poll::Pending => {}`
803         let pending_arm = {
804             let pending_pat = self.pat_lang_item_variant(span, hir::LangItem::PollPending, &[]);
805             let empty_block = self.expr_block_empty(span);
806             self.arm(pending_pat, empty_block)
807         };
808
809         let inner_match_stmt = {
810             let match_expr = self.expr_match(
811                 span,
812                 poll_expr,
813                 arena_vec![self; ready_arm, pending_arm],
814                 hir::MatchSource::AwaitDesugar,
815             );
816             self.stmt_expr(span, match_expr)
817         };
818
819         // task_context = yield ();
820         let yield_stmt = {
821             let unit = self.expr_unit(span);
822             let yield_expr = self.expr(
823                 span,
824                 hir::ExprKind::Yield(unit, hir::YieldSource::Await { expr: Some(expr.hir_id) }),
825                 ThinVec::new(),
826             );
827             let yield_expr = self.arena.alloc(yield_expr);
828
829             if let Some(task_context_hid) = self.task_context {
830                 let lhs = self.expr_ident(span, task_context_ident, task_context_hid);
831                 let assign =
832                     self.expr(span, hir::ExprKind::Assign(lhs, yield_expr, span), AttrVec::new());
833                 self.stmt_expr(span, assign)
834             } else {
835                 // Use of `await` outside of an async context. Return `yield_expr` so that we can
836                 // proceed with type checking.
837                 self.stmt(span, hir::StmtKind::Semi(yield_expr))
838             }
839         };
840
841         let loop_block = self.block_all(span, arena_vec![self; inner_match_stmt, yield_stmt], None);
842
843         // loop { .. }
844         let loop_expr = self.arena.alloc(hir::Expr {
845             hir_id: loop_hir_id,
846             kind: hir::ExprKind::Loop(loop_block, None, hir::LoopSource::Loop, span),
847             span,
848         });
849
850         // mut pinned => loop { ... }
851         let pinned_arm = self.arm(pinned_pat, loop_expr);
852
853         // match <expr> {
854         //     mut pinned => loop { .. }
855         // }
856         hir::ExprKind::Match(expr, arena_vec![self; pinned_arm], hir::MatchSource::AwaitDesugar)
857     }
858
859     fn lower_expr_closure(
860         &mut self,
861         capture_clause: CaptureBy,
862         movability: Movability,
863         decl: &FnDecl,
864         body: &Expr,
865         fn_decl_span: Span,
866     ) -> hir::ExprKind<'hir> {
867         let (body_id, generator_option) = self.with_new_scopes(move |this| {
868             let prev = this.current_item;
869             this.current_item = Some(fn_decl_span);
870             let mut generator_kind = None;
871             let body_id = this.lower_fn_body(decl, |this| {
872                 let e = this.lower_expr_mut(body);
873                 generator_kind = this.generator_kind;
874                 e
875             });
876             let generator_option =
877                 this.generator_movability_for_fn(&decl, fn_decl_span, generator_kind, movability);
878             this.current_item = prev;
879             (body_id, generator_option)
880         });
881
882         // Lower outside new scope to preserve `is_in_loop_condition`.
883         let fn_decl = self.lower_fn_decl(decl, None, false, None);
884
885         hir::ExprKind::Closure(capture_clause, fn_decl, body_id, fn_decl_span, generator_option)
886     }
887
888     fn generator_movability_for_fn(
889         &mut self,
890         decl: &FnDecl,
891         fn_decl_span: Span,
892         generator_kind: Option<hir::GeneratorKind>,
893         movability: Movability,
894     ) -> Option<hir::Movability> {
895         match generator_kind {
896             Some(hir::GeneratorKind::Gen) => {
897                 if decl.inputs.len() > 1 {
898                     struct_span_err!(
899                         self.sess,
900                         fn_decl_span,
901                         E0628,
902                         "too many parameters for a generator (expected 0 or 1 parameters)"
903                     )
904                     .emit();
905                 }
906                 Some(movability)
907             }
908             Some(hir::GeneratorKind::Async(_)) => {
909                 panic!("non-`async` closure body turned `async` during lowering");
910             }
911             None => {
912                 if movability == Movability::Static {
913                     struct_span_err!(self.sess, fn_decl_span, E0697, "closures cannot be static")
914                         .emit();
915                 }
916                 None
917             }
918         }
919     }
920
921     fn lower_expr_async_closure(
922         &mut self,
923         capture_clause: CaptureBy,
924         closure_id: NodeId,
925         decl: &FnDecl,
926         body: &Expr,
927         fn_decl_span: Span,
928     ) -> hir::ExprKind<'hir> {
929         let outer_decl =
930             FnDecl { inputs: decl.inputs.clone(), output: FnRetTy::Default(fn_decl_span) };
931
932         let body_id = self.with_new_scopes(|this| {
933             // FIXME(cramertj): allow `async` non-`move` closures with arguments.
934             if capture_clause == CaptureBy::Ref && !decl.inputs.is_empty() {
935                 struct_span_err!(
936                     this.sess,
937                     fn_decl_span,
938                     E0708,
939                     "`async` non-`move` closures with parameters are not currently supported",
940                 )
941                 .help(
942                     "consider using `let` statements to manually capture \
943                     variables by reference before entering an `async move` closure",
944                 )
945                 .emit();
946             }
947
948             // Transform `async |x: u8| -> X { ... }` into
949             // `|x: u8| future_from_generator(|| -> X { ... })`.
950             let body_id = this.lower_fn_body(&outer_decl, |this| {
951                 let async_ret_ty =
952                     if let FnRetTy::Ty(ty) = &decl.output { Some(ty.clone()) } else { None };
953                 let async_body = this.make_async_expr(
954                     capture_clause,
955                     closure_id,
956                     async_ret_ty,
957                     body.span,
958                     hir::AsyncGeneratorKind::Closure,
959                     |this| this.with_new_scopes(|this| this.lower_expr_mut(body)),
960                 );
961                 this.expr(fn_decl_span, async_body, ThinVec::new())
962             });
963             body_id
964         });
965
966         // We need to lower the declaration outside the new scope, because we
967         // have to conserve the state of being inside a loop condition for the
968         // closure argument types.
969         let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
970
971         hir::ExprKind::Closure(capture_clause, fn_decl, body_id, fn_decl_span, None)
972     }
973
974     /// Destructure the LHS of complex assignments.
975     /// For instance, lower `(a, b) = t` to `{ let (lhs1, lhs2) = t; a = lhs1; b = lhs2; }`.
976     fn lower_expr_assign(
977         &mut self,
978         lhs: &Expr,
979         rhs: &Expr,
980         eq_sign_span: Span,
981         whole_span: Span,
982     ) -> hir::ExprKind<'hir> {
983         // Return early in case of an ordinary assignment.
984         fn is_ordinary(lower_ctx: &mut LoweringContext<'_, '_>, lhs: &Expr) -> bool {
985             match &lhs.kind {
986                 ExprKind::Array(..)
987                 | ExprKind::Struct(..)
988                 | ExprKind::Tup(..)
989                 | ExprKind::Underscore => false,
990                 // Check for tuple struct constructor.
991                 ExprKind::Call(callee, ..) => lower_ctx.extract_tuple_struct_path(callee).is_none(),
992                 ExprKind::Paren(e) => {
993                     match e.kind {
994                         // We special-case `(..)` for consistency with patterns.
995                         ExprKind::Range(None, None, RangeLimits::HalfOpen) => false,
996                         _ => is_ordinary(lower_ctx, e),
997                     }
998                 }
999                 _ => true,
1000             }
1001         }
1002         if is_ordinary(self, lhs) {
1003             return hir::ExprKind::Assign(self.lower_expr(lhs), self.lower_expr(rhs), eq_sign_span);
1004         }
1005         if !self.sess.features_untracked().destructuring_assignment {
1006             feature_err(
1007                 &self.sess.parse_sess,
1008                 sym::destructuring_assignment,
1009                 eq_sign_span,
1010                 "destructuring assignments are unstable",
1011             )
1012             .span_label(lhs.span, "cannot assign to this expression")
1013             .emit();
1014         }
1015
1016         let mut assignments = vec![];
1017
1018         // The LHS becomes a pattern: `(lhs1, lhs2)`.
1019         let pat = self.destructure_assign(lhs, eq_sign_span, &mut assignments);
1020         let rhs = self.lower_expr(rhs);
1021
1022         // Introduce a `let` for destructuring: `let (lhs1, lhs2) = t`.
1023         let destructure_let = self.stmt_let_pat(
1024             None,
1025             whole_span,
1026             Some(rhs),
1027             pat,
1028             hir::LocalSource::AssignDesugar(eq_sign_span),
1029         );
1030
1031         // `a = lhs1; b = lhs2;`.
1032         let stmts = self
1033             .arena
1034             .alloc_from_iter(std::iter::once(destructure_let).chain(assignments.into_iter()));
1035
1036         // Wrap everything in a block.
1037         hir::ExprKind::Block(&self.block_all(whole_span, stmts, None), None)
1038     }
1039
1040     /// If the given expression is a path to a tuple struct, returns that path.
1041     /// It is not a complete check, but just tries to reject most paths early
1042     /// if they are not tuple structs.
1043     /// Type checking will take care of the full validation later.
1044     fn extract_tuple_struct_path<'a>(
1045         &mut self,
1046         expr: &'a Expr,
1047     ) -> Option<(&'a Option<QSelf>, &'a Path)> {
1048         if let ExprKind::Path(qself, path) = &expr.kind {
1049             // Does the path resolve to something disallowed in a tuple struct/variant pattern?
1050             if let Some(partial_res) = self.resolver.get_partial_res(expr.id) {
1051                 if partial_res.unresolved_segments() == 0
1052                     && !partial_res.base_res().expected_in_tuple_struct_pat()
1053                 {
1054                     return None;
1055                 }
1056             }
1057             return Some((qself, path));
1058         }
1059         None
1060     }
1061
1062     /// Convert the LHS of a destructuring assignment to a pattern.
1063     /// Each sub-assignment is recorded in `assignments`.
1064     fn destructure_assign(
1065         &mut self,
1066         lhs: &Expr,
1067         eq_sign_span: Span,
1068         assignments: &mut Vec<hir::Stmt<'hir>>,
1069     ) -> &'hir hir::Pat<'hir> {
1070         match &lhs.kind {
1071             // Underscore pattern.
1072             ExprKind::Underscore => {
1073                 return self.pat_without_dbm(lhs.span, hir::PatKind::Wild);
1074             }
1075             // Slice patterns.
1076             ExprKind::Array(elements) => {
1077                 let (pats, rest) =
1078                     self.destructure_sequence(elements, "slice", eq_sign_span, assignments);
1079                 let slice_pat = if let Some((i, span)) = rest {
1080                     let (before, after) = pats.split_at(i);
1081                     hir::PatKind::Slice(
1082                         before,
1083                         Some(self.pat_without_dbm(span, hir::PatKind::Wild)),
1084                         after,
1085                     )
1086                 } else {
1087                     hir::PatKind::Slice(pats, None, &[])
1088                 };
1089                 return self.pat_without_dbm(lhs.span, slice_pat);
1090             }
1091             // Tuple structs.
1092             ExprKind::Call(callee, args) => {
1093                 if let Some((qself, path)) = self.extract_tuple_struct_path(callee) {
1094                     let (pats, rest) = self.destructure_sequence(
1095                         args,
1096                         "tuple struct or variant",
1097                         eq_sign_span,
1098                         assignments,
1099                     );
1100                     let qpath = self.lower_qpath(
1101                         callee.id,
1102                         qself,
1103                         path,
1104                         ParamMode::Optional,
1105                         ImplTraitContext::disallowed(),
1106                     );
1107                     // Destructure like a tuple struct.
1108                     let tuple_struct_pat =
1109                         hir::PatKind::TupleStruct(qpath, pats, rest.map(|r| r.0));
1110                     return self.pat_without_dbm(lhs.span, tuple_struct_pat);
1111                 }
1112             }
1113             // Structs.
1114             ExprKind::Struct(se) => {
1115                 let field_pats = self.arena.alloc_from_iter(se.fields.iter().map(|f| {
1116                     let pat = self.destructure_assign(&f.expr, eq_sign_span, assignments);
1117                     hir::PatField {
1118                         hir_id: self.next_id(),
1119                         ident: f.ident,
1120                         pat,
1121                         is_shorthand: f.is_shorthand,
1122                         span: f.span,
1123                     }
1124                 }));
1125                 let qpath = self.lower_qpath(
1126                     lhs.id,
1127                     &se.qself,
1128                     &se.path,
1129                     ParamMode::Optional,
1130                     ImplTraitContext::disallowed(),
1131                 );
1132                 let fields_omitted = match &se.rest {
1133                     StructRest::Base(e) => {
1134                         self.sess
1135                             .struct_span_err(
1136                                 e.span,
1137                                 "functional record updates are not allowed in destructuring \
1138                                     assignments",
1139                             )
1140                             .span_suggestion(
1141                                 e.span,
1142                                 "consider removing the trailing pattern",
1143                                 String::new(),
1144                                 rustc_errors::Applicability::MachineApplicable,
1145                             )
1146                             .emit();
1147                         true
1148                     }
1149                     StructRest::Rest(_) => true,
1150                     StructRest::None => false,
1151                 };
1152                 let struct_pat = hir::PatKind::Struct(qpath, field_pats, fields_omitted);
1153                 return self.pat_without_dbm(lhs.span, struct_pat);
1154             }
1155             // Tuples.
1156             ExprKind::Tup(elements) => {
1157                 let (pats, rest) =
1158                     self.destructure_sequence(elements, "tuple", eq_sign_span, assignments);
1159                 let tuple_pat = hir::PatKind::Tuple(pats, rest.map(|r| r.0));
1160                 return self.pat_without_dbm(lhs.span, tuple_pat);
1161             }
1162             ExprKind::Paren(e) => {
1163                 // We special-case `(..)` for consistency with patterns.
1164                 if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
1165                     let tuple_pat = hir::PatKind::Tuple(&[], Some(0));
1166                     return self.pat_without_dbm(lhs.span, tuple_pat);
1167                 } else {
1168                     return self.destructure_assign(e, eq_sign_span, assignments);
1169                 }
1170             }
1171             _ => {}
1172         }
1173         // Treat all other cases as normal lvalue.
1174         let ident = Ident::new(sym::lhs, lhs.span);
1175         let (pat, binding) = self.pat_ident(lhs.span, ident);
1176         let ident = self.expr_ident(lhs.span, ident, binding);
1177         let assign = hir::ExprKind::Assign(self.lower_expr(lhs), ident, eq_sign_span);
1178         let expr = self.expr(lhs.span, assign, ThinVec::new());
1179         assignments.push(self.stmt_expr(lhs.span, expr));
1180         pat
1181     }
1182
1183     /// Destructure a sequence of expressions occurring on the LHS of an assignment.
1184     /// Such a sequence occurs in a tuple (struct)/slice.
1185     /// Return a sequence of corresponding patterns, and the index and the span of `..` if it
1186     /// exists.
1187     /// Each sub-assignment is recorded in `assignments`.
1188     fn destructure_sequence(
1189         &mut self,
1190         elements: &[AstP<Expr>],
1191         ctx: &str,
1192         eq_sign_span: Span,
1193         assignments: &mut Vec<hir::Stmt<'hir>>,
1194     ) -> (&'hir [&'hir hir::Pat<'hir>], Option<(usize, Span)>) {
1195         let mut rest = None;
1196         let elements =
1197             self.arena.alloc_from_iter(elements.iter().enumerate().filter_map(|(i, e)| {
1198                 // Check for `..` pattern.
1199                 if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
1200                     if let Some((_, prev_span)) = rest {
1201                         self.ban_extra_rest_pat(e.span, prev_span, ctx);
1202                     } else {
1203                         rest = Some((i, e.span));
1204                     }
1205                     None
1206                 } else {
1207                     Some(self.destructure_assign(e, eq_sign_span, assignments))
1208                 }
1209             }));
1210         (elements, rest)
1211     }
1212
1213     /// Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`.
1214     fn lower_expr_range_closed(&mut self, span: Span, e1: &Expr, e2: &Expr) -> hir::ExprKind<'hir> {
1215         let e1 = self.lower_expr_mut(e1);
1216         let e2 = self.lower_expr_mut(e2);
1217         let fn_path = hir::QPath::LangItem(hir::LangItem::RangeInclusiveNew, span);
1218         let fn_expr =
1219             self.arena.alloc(self.expr(span, hir::ExprKind::Path(fn_path), ThinVec::new()));
1220         hir::ExprKind::Call(fn_expr, arena_vec![self; e1, e2])
1221     }
1222
1223     fn lower_expr_range(
1224         &mut self,
1225         span: Span,
1226         e1: Option<&Expr>,
1227         e2: Option<&Expr>,
1228         lims: RangeLimits,
1229     ) -> hir::ExprKind<'hir> {
1230         use rustc_ast::RangeLimits::*;
1231
1232         let lang_item = match (e1, e2, lims) {
1233             (None, None, HalfOpen) => hir::LangItem::RangeFull,
1234             (Some(..), None, HalfOpen) => hir::LangItem::RangeFrom,
1235             (None, Some(..), HalfOpen) => hir::LangItem::RangeTo,
1236             (Some(..), Some(..), HalfOpen) => hir::LangItem::Range,
1237             (None, Some(..), Closed) => hir::LangItem::RangeToInclusive,
1238             (Some(..), Some(..), Closed) => unreachable!(),
1239             (_, None, Closed) => self.diagnostic().span_fatal(span, "inclusive range with no end"),
1240         };
1241
1242         let fields = self.arena.alloc_from_iter(
1243             e1.iter().map(|e| ("start", e)).chain(e2.iter().map(|e| ("end", e))).map(|(s, e)| {
1244                 let expr = self.lower_expr(&e);
1245                 let ident = Ident::new(Symbol::intern(s), e.span);
1246                 self.expr_field(ident, expr, e.span)
1247             }),
1248         );
1249
1250         hir::ExprKind::Struct(self.arena.alloc(hir::QPath::LangItem(lang_item, span)), fields, None)
1251     }
1252
1253     fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
1254         let target_id = match destination {
1255             Some((id, _)) => {
1256                 if let Some(loop_id) = self.resolver.get_label_res(id) {
1257                     Ok(self.lower_node_id(loop_id))
1258                 } else {
1259                     Err(hir::LoopIdError::UnresolvedLabel)
1260                 }
1261             }
1262             None => self
1263                 .loop_scopes
1264                 .last()
1265                 .cloned()
1266                 .map(|id| Ok(self.lower_node_id(id)))
1267                 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope)),
1268         };
1269         hir::Destination { label: destination.map(|(_, label)| label), target_id }
1270     }
1271
1272     fn lower_jump_destination(&mut self, id: NodeId, opt_label: Option<Label>) -> hir::Destination {
1273         if self.is_in_loop_condition && opt_label.is_none() {
1274             hir::Destination {
1275                 label: None,
1276                 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition),
1277             }
1278         } else {
1279             self.lower_loop_destination(opt_label.map(|label| (id, label)))
1280         }
1281     }
1282
1283     fn with_catch_scope<T>(&mut self, catch_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1284         let len = self.catch_scopes.len();
1285         self.catch_scopes.push(catch_id);
1286
1287         let result = f(self);
1288         assert_eq!(
1289             len + 1,
1290             self.catch_scopes.len(),
1291             "catch scopes should be added and removed in stack order"
1292         );
1293
1294         self.catch_scopes.pop().unwrap();
1295
1296         result
1297     }
1298
1299     fn with_loop_scope<T>(&mut self, loop_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1300         // We're no longer in the base loop's condition; we're in another loop.
1301         let was_in_loop_condition = self.is_in_loop_condition;
1302         self.is_in_loop_condition = false;
1303
1304         let len = self.loop_scopes.len();
1305         self.loop_scopes.push(loop_id);
1306
1307         let result = f(self);
1308         assert_eq!(
1309             len + 1,
1310             self.loop_scopes.len(),
1311             "loop scopes should be added and removed in stack order"
1312         );
1313
1314         self.loop_scopes.pop().unwrap();
1315
1316         self.is_in_loop_condition = was_in_loop_condition;
1317
1318         result
1319     }
1320
1321     fn with_loop_condition_scope<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
1322         let was_in_loop_condition = self.is_in_loop_condition;
1323         self.is_in_loop_condition = true;
1324
1325         let result = f(self);
1326
1327         self.is_in_loop_condition = was_in_loop_condition;
1328
1329         result
1330     }
1331
1332     fn lower_expr_llvm_asm(&mut self, asm: &LlvmInlineAsm) -> hir::ExprKind<'hir> {
1333         let inner = hir::LlvmInlineAsmInner {
1334             inputs: asm.inputs.iter().map(|&(c, _)| c).collect(),
1335             outputs: asm
1336                 .outputs
1337                 .iter()
1338                 .map(|out| hir::LlvmInlineAsmOutput {
1339                     constraint: out.constraint,
1340                     is_rw: out.is_rw,
1341                     is_indirect: out.is_indirect,
1342                     span: out.expr.span,
1343                 })
1344                 .collect(),
1345             asm: asm.asm,
1346             asm_str_style: asm.asm_str_style,
1347             clobbers: asm.clobbers.clone(),
1348             volatile: asm.volatile,
1349             alignstack: asm.alignstack,
1350             dialect: asm.dialect,
1351         };
1352         let hir_asm = hir::LlvmInlineAsm {
1353             inner,
1354             inputs_exprs: self.arena.alloc_from_iter(
1355                 asm.inputs.iter().map(|&(_, ref input)| self.lower_expr_mut(input)),
1356             ),
1357             outputs_exprs: self
1358                 .arena
1359                 .alloc_from_iter(asm.outputs.iter().map(|out| self.lower_expr_mut(&out.expr))),
1360         };
1361         hir::ExprKind::LlvmInlineAsm(self.arena.alloc(hir_asm))
1362     }
1363
1364     fn lower_expr_field(&mut self, f: &ExprField) -> hir::ExprField<'hir> {
1365         hir::ExprField {
1366             hir_id: self.next_id(),
1367             ident: f.ident,
1368             expr: self.lower_expr(&f.expr),
1369             span: f.span,
1370             is_shorthand: f.is_shorthand,
1371         }
1372     }
1373
1374     fn lower_expr_yield(&mut self, span: Span, opt_expr: Option<&Expr>) -> hir::ExprKind<'hir> {
1375         match self.generator_kind {
1376             Some(hir::GeneratorKind::Gen) => {}
1377             Some(hir::GeneratorKind::Async(_)) => {
1378                 struct_span_err!(
1379                     self.sess,
1380                     span,
1381                     E0727,
1382                     "`async` generators are not yet supported"
1383                 )
1384                 .emit();
1385             }
1386             None => self.generator_kind = Some(hir::GeneratorKind::Gen),
1387         }
1388
1389         let expr =
1390             opt_expr.as_ref().map(|x| self.lower_expr(x)).unwrap_or_else(|| self.expr_unit(span));
1391
1392         hir::ExprKind::Yield(expr, hir::YieldSource::Yield)
1393     }
1394
1395     /// Desugar `ExprForLoop` from: `[opt_ident]: for <pat> in <head> <body>` into:
1396     /// ```rust
1397     /// {
1398     ///     let result = match ::std::iter::IntoIterator::into_iter(<head>) {
1399     ///         mut iter => {
1400     ///             [opt_ident]: loop {
1401     ///                 let mut __next;
1402     ///                 match ::std::iter::Iterator::next(&mut iter) {
1403     ///                     ::std::option::Option::Some(val) => __next = val,
1404     ///                     ::std::option::Option::None => break
1405     ///                 };
1406     ///                 let <pat> = __next;
1407     ///                 StmtKind::Expr(<body>);
1408     ///             }
1409     ///         }
1410     ///     };
1411     ///     result
1412     /// }
1413     /// ```
1414     fn lower_expr_for(
1415         &mut self,
1416         e: &Expr,
1417         pat: &Pat,
1418         head: &Expr,
1419         body: &Block,
1420         opt_label: Option<Label>,
1421     ) -> hir::Expr<'hir> {
1422         let orig_head_span = head.span;
1423         // expand <head>
1424         let mut head = self.lower_expr_mut(head);
1425         let desugared_span = self.mark_span_with_reason(
1426             DesugaringKind::ForLoop(ForLoopLoc::Head),
1427             orig_head_span,
1428             None,
1429         );
1430         head.span = desugared_span;
1431
1432         let iter = Ident::with_dummy_span(sym::iter);
1433
1434         let next_ident = Ident::with_dummy_span(sym::__next);
1435         let (next_pat, next_pat_hid) = self.pat_ident_binding_mode(
1436             desugared_span,
1437             next_ident,
1438             hir::BindingAnnotation::Mutable,
1439         );
1440
1441         // `::std::option::Option::Some(val) => __next = val`
1442         let pat_arm = {
1443             let val_ident = Ident::with_dummy_span(sym::val);
1444             let (val_pat, val_pat_hid) = self.pat_ident(pat.span, val_ident);
1445             let val_expr = self.expr_ident(pat.span, val_ident, val_pat_hid);
1446             let next_expr = self.expr_ident(pat.span, next_ident, next_pat_hid);
1447             let assign = self.arena.alloc(self.expr(
1448                 pat.span,
1449                 hir::ExprKind::Assign(next_expr, val_expr, pat.span),
1450                 ThinVec::new(),
1451             ));
1452             let some_pat = self.pat_some(pat.span, val_pat);
1453             self.arm(some_pat, assign)
1454         };
1455
1456         // `::std::option::Option::None => break`
1457         let break_arm = {
1458             let break_expr =
1459                 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
1460             let pat = self.pat_none(e.span);
1461             self.arm(pat, break_expr)
1462         };
1463
1464         // `mut iter`
1465         let (iter_pat, iter_pat_nid) =
1466             self.pat_ident_binding_mode(desugared_span, iter, hir::BindingAnnotation::Mutable);
1467
1468         // `match ::std::iter::Iterator::next(&mut iter) { ... }`
1469         let match_expr = {
1470             let iter = self.expr_ident(desugared_span, iter, iter_pat_nid);
1471             let ref_mut_iter = self.expr_mut_addr_of(desugared_span, iter);
1472             let next_expr = self.expr_call_lang_item_fn(
1473                 desugared_span,
1474                 hir::LangItem::IteratorNext,
1475                 arena_vec![self; ref_mut_iter],
1476             );
1477             let arms = arena_vec![self; pat_arm, break_arm];
1478
1479             self.expr_match(desugared_span, next_expr, arms, hir::MatchSource::ForLoopDesugar)
1480         };
1481         let match_stmt = self.stmt_expr(desugared_span, match_expr);
1482
1483         let next_expr = self.expr_ident(desugared_span, next_ident, next_pat_hid);
1484
1485         // `let mut __next`
1486         let next_let = self.stmt_let_pat(
1487             None,
1488             desugared_span,
1489             None,
1490             next_pat,
1491             hir::LocalSource::ForLoopDesugar,
1492         );
1493
1494         // `let <pat> = __next`
1495         let pat = self.lower_pat(pat);
1496         let pat_let = self.stmt_let_pat(
1497             None,
1498             desugared_span,
1499             Some(next_expr),
1500             pat,
1501             hir::LocalSource::ForLoopDesugar,
1502         );
1503
1504         let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
1505         let body_expr = self.expr_block(body_block, ThinVec::new());
1506         let body_stmt = self.stmt_expr(body.span, body_expr);
1507
1508         let loop_block = self.block_all(
1509             e.span,
1510             arena_vec![self; next_let, match_stmt, pat_let, body_stmt],
1511             None,
1512         );
1513
1514         // `[opt_ident]: loop { ... }`
1515         let kind = hir::ExprKind::Loop(
1516             loop_block,
1517             opt_label,
1518             hir::LoopSource::ForLoop,
1519             e.span.with_hi(orig_head_span.hi()),
1520         );
1521         let loop_expr =
1522             self.arena.alloc(hir::Expr { hir_id: self.lower_node_id(e.id), kind, span: e.span });
1523
1524         // `mut iter => { ... }`
1525         let iter_arm = self.arm(iter_pat, loop_expr);
1526
1527         let into_iter_span = self.mark_span_with_reason(
1528             DesugaringKind::ForLoop(ForLoopLoc::IntoIter),
1529             orig_head_span,
1530             None,
1531         );
1532
1533         // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
1534         let into_iter_expr = {
1535             self.expr_call_lang_item_fn(
1536                 into_iter_span,
1537                 hir::LangItem::IntoIterIntoIter,
1538                 arena_vec![self; head],
1539             )
1540         };
1541
1542         let match_expr = self.arena.alloc(self.expr_match(
1543             desugared_span,
1544             into_iter_expr,
1545             arena_vec![self; iter_arm],
1546             hir::MatchSource::ForLoopDesugar,
1547         ));
1548
1549         let attrs: Vec<_> = e.attrs.iter().map(|a| self.lower_attr(a)).collect();
1550
1551         // This is effectively `{ let _result = ...; _result }`.
1552         // The construct was introduced in #21984 and is necessary to make sure that
1553         // temporaries in the `head` expression are dropped and do not leak to the
1554         // surrounding scope of the `match` since the `match` is not a terminating scope.
1555         //
1556         // Also, add the attributes to the outer returned expr node.
1557         self.expr_drop_temps_mut(desugared_span, match_expr, attrs.into())
1558     }
1559
1560     /// Desugar `ExprKind::Try` from: `<expr>?` into:
1561     /// ```rust
1562     /// match Try::into_result(<expr>) {
1563     ///     Ok(val) => #[allow(unreachable_code)] val,
1564     ///     Err(err) => #[allow(unreachable_code)]
1565     ///                 // If there is an enclosing `try {...}`:
1566     ///                 break 'catch_target Try::from_error(From::from(err)),
1567     ///                 // Otherwise:
1568     ///                 return Try::from_error(From::from(err)),
1569     /// }
1570     /// ```
1571     fn lower_expr_try(&mut self, span: Span, sub_expr: &Expr) -> hir::ExprKind<'hir> {
1572         let unstable_span = self.mark_span_with_reason(
1573             DesugaringKind::QuestionMark,
1574             span,
1575             self.allow_try_trait.clone(),
1576         );
1577         let try_span = self.sess.source_map().end_point(span);
1578         let try_span = self.mark_span_with_reason(
1579             DesugaringKind::QuestionMark,
1580             try_span,
1581             self.allow_try_trait.clone(),
1582         );
1583
1584         // `Try::branch(<expr>)`
1585         let scrutinee = {
1586             // expand <expr>
1587             let sub_expr = self.lower_expr_mut(sub_expr);
1588
1589             self.expr_call_lang_item_fn(
1590                 unstable_span,
1591                 hir::LangItem::TryTraitBranch,
1592                 arena_vec![self; sub_expr],
1593             )
1594         };
1595
1596         // `#[allow(unreachable_code)]`
1597         let attr = {
1598             // `allow(unreachable_code)`
1599             let allow = {
1600                 let allow_ident = Ident::new(sym::allow, span);
1601                 let uc_ident = Ident::new(sym::unreachable_code, span);
1602                 let uc_nested = attr::mk_nested_word_item(uc_ident);
1603                 attr::mk_list_item(allow_ident, vec![uc_nested])
1604             };
1605             attr::mk_attr_outer(allow)
1606         };
1607         let attrs = vec![attr];
1608
1609         // `ControlFlow::Continue(val) => #[allow(unreachable_code)] val,`
1610         let continue_arm = {
1611             let val_ident = Ident::with_dummy_span(sym::val);
1612             let (val_pat, val_pat_nid) = self.pat_ident(span, val_ident);
1613             let val_expr = self.arena.alloc(self.expr_ident_with_attrs(
1614                 span,
1615                 val_ident,
1616                 val_pat_nid,
1617                 ThinVec::from(attrs.clone()),
1618             ));
1619             let continue_pat = self.pat_cf_continue(unstable_span, val_pat);
1620             self.arm(continue_pat, val_expr)
1621         };
1622
1623         // `ControlFlow::Break(residual) =>
1624         //     #[allow(unreachable_code)]
1625         //     return Try::from_residual(residual),`
1626         let break_arm = {
1627             let residual_ident = Ident::with_dummy_span(sym::residual);
1628             let (residual_local, residual_local_nid) = self.pat_ident(try_span, residual_ident);
1629             let residual_expr = self.expr_ident_mut(try_span, residual_ident, residual_local_nid);
1630             let from_residual_expr = self.wrap_in_try_constructor(
1631                 hir::LangItem::TryTraitFromResidual,
1632                 try_span,
1633                 self.arena.alloc(residual_expr),
1634                 unstable_span,
1635             );
1636             let thin_attrs = ThinVec::from(attrs);
1637             let catch_scope = self.catch_scopes.last().copied();
1638             let ret_expr = if let Some(catch_node) = catch_scope {
1639                 let target_id = Ok(self.lower_node_id(catch_node));
1640                 self.arena.alloc(self.expr(
1641                     try_span,
1642                     hir::ExprKind::Break(
1643                         hir::Destination { label: None, target_id },
1644                         Some(from_residual_expr),
1645                     ),
1646                     thin_attrs,
1647                 ))
1648             } else {
1649                 self.arena.alloc(self.expr(
1650                     try_span,
1651                     hir::ExprKind::Ret(Some(from_residual_expr)),
1652                     thin_attrs,
1653                 ))
1654             };
1655
1656             let break_pat = self.pat_cf_break(try_span, residual_local);
1657             self.arm(break_pat, ret_expr)
1658         };
1659
1660         hir::ExprKind::Match(
1661             scrutinee,
1662             arena_vec![self; break_arm, continue_arm],
1663             hir::MatchSource::TryDesugar,
1664         )
1665     }
1666
1667     // =========================================================================
1668     // Helper methods for building HIR.
1669     // =========================================================================
1670
1671     /// Constructs a `true` or `false` literal expression.
1672     pub(super) fn expr_bool(&mut self, span: Span, val: bool) -> &'hir hir::Expr<'hir> {
1673         let lit = Spanned { span, node: LitKind::Bool(val) };
1674         self.arena.alloc(self.expr(span, hir::ExprKind::Lit(lit), ThinVec::new()))
1675     }
1676
1677     /// Wrap the given `expr` in a terminating scope using `hir::ExprKind::DropTemps`.
1678     ///
1679     /// In terms of drop order, it has the same effect as wrapping `expr` in
1680     /// `{ let _t = $expr; _t }` but should provide better compile-time performance.
1681     ///
1682     /// The drop order can be important in e.g. `if expr { .. }`.
1683     pub(super) fn expr_drop_temps(
1684         &mut self,
1685         span: Span,
1686         expr: &'hir hir::Expr<'hir>,
1687         attrs: AttrVec,
1688     ) -> &'hir hir::Expr<'hir> {
1689         self.arena.alloc(self.expr_drop_temps_mut(span, expr, attrs))
1690     }
1691
1692     pub(super) fn expr_drop_temps_mut(
1693         &mut self,
1694         span: Span,
1695         expr: &'hir hir::Expr<'hir>,
1696         attrs: AttrVec,
1697     ) -> hir::Expr<'hir> {
1698         self.expr(span, hir::ExprKind::DropTemps(expr), attrs)
1699     }
1700
1701     fn expr_match(
1702         &mut self,
1703         span: Span,
1704         arg: &'hir hir::Expr<'hir>,
1705         arms: &'hir [hir::Arm<'hir>],
1706         source: hir::MatchSource,
1707     ) -> hir::Expr<'hir> {
1708         self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
1709     }
1710
1711     fn expr_break(&mut self, span: Span, attrs: AttrVec) -> &'hir hir::Expr<'hir> {
1712         let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
1713         self.arena.alloc(self.expr(span, expr_break, attrs))
1714     }
1715
1716     fn expr_mut_addr_of(&mut self, span: Span, e: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
1717         self.expr(
1718             span,
1719             hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Mut, e),
1720             ThinVec::new(),
1721         )
1722     }
1723
1724     fn expr_unit(&mut self, sp: Span) -> &'hir hir::Expr<'hir> {
1725         self.arena.alloc(self.expr(sp, hir::ExprKind::Tup(&[]), ThinVec::new()))
1726     }
1727
1728     fn expr_call_mut(
1729         &mut self,
1730         span: Span,
1731         e: &'hir hir::Expr<'hir>,
1732         args: &'hir [hir::Expr<'hir>],
1733     ) -> hir::Expr<'hir> {
1734         self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
1735     }
1736
1737     fn expr_call(
1738         &mut self,
1739         span: Span,
1740         e: &'hir hir::Expr<'hir>,
1741         args: &'hir [hir::Expr<'hir>],
1742     ) -> &'hir hir::Expr<'hir> {
1743         self.arena.alloc(self.expr_call_mut(span, e, args))
1744     }
1745
1746     fn expr_call_lang_item_fn_mut(
1747         &mut self,
1748         span: Span,
1749         lang_item: hir::LangItem,
1750         args: &'hir [hir::Expr<'hir>],
1751     ) -> hir::Expr<'hir> {
1752         let path = self.arena.alloc(self.expr_lang_item_path(span, lang_item, ThinVec::new()));
1753         self.expr_call_mut(span, path, args)
1754     }
1755
1756     fn expr_call_lang_item_fn(
1757         &mut self,
1758         span: Span,
1759         lang_item: hir::LangItem,
1760         args: &'hir [hir::Expr<'hir>],
1761     ) -> &'hir hir::Expr<'hir> {
1762         self.arena.alloc(self.expr_call_lang_item_fn_mut(span, lang_item, args))
1763     }
1764
1765     fn expr_lang_item_path(
1766         &mut self,
1767         span: Span,
1768         lang_item: hir::LangItem,
1769         attrs: AttrVec,
1770     ) -> hir::Expr<'hir> {
1771         self.expr(span, hir::ExprKind::Path(hir::QPath::LangItem(lang_item, span)), attrs)
1772     }
1773
1774     pub(super) fn expr_ident(
1775         &mut self,
1776         sp: Span,
1777         ident: Ident,
1778         binding: hir::HirId,
1779     ) -> &'hir hir::Expr<'hir> {
1780         self.arena.alloc(self.expr_ident_mut(sp, ident, binding))
1781     }
1782
1783     pub(super) fn expr_ident_mut(
1784         &mut self,
1785         sp: Span,
1786         ident: Ident,
1787         binding: hir::HirId,
1788     ) -> hir::Expr<'hir> {
1789         self.expr_ident_with_attrs(sp, ident, binding, ThinVec::new())
1790     }
1791
1792     fn expr_ident_with_attrs(
1793         &mut self,
1794         span: Span,
1795         ident: Ident,
1796         binding: hir::HirId,
1797         attrs: AttrVec,
1798     ) -> hir::Expr<'hir> {
1799         let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
1800             None,
1801             self.arena.alloc(hir::Path {
1802                 span,
1803                 res: Res::Local(binding),
1804                 segments: arena_vec![self; hir::PathSegment::from_ident(ident)],
1805             }),
1806         ));
1807
1808         self.expr(span, expr_path, attrs)
1809     }
1810
1811     fn expr_unsafe(&mut self, expr: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
1812         let hir_id = self.next_id();
1813         let span = expr.span;
1814         self.expr(
1815             span,
1816             hir::ExprKind::Block(
1817                 self.arena.alloc(hir::Block {
1818                     stmts: &[],
1819                     expr: Some(expr),
1820                     hir_id,
1821                     rules: hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::CompilerGenerated),
1822                     span,
1823                     targeted_by_break: false,
1824                 }),
1825                 None,
1826             ),
1827             ThinVec::new(),
1828         )
1829     }
1830
1831     fn expr_block_empty(&mut self, span: Span) -> &'hir hir::Expr<'hir> {
1832         let blk = self.block_all(span, &[], None);
1833         let expr = self.expr_block(blk, ThinVec::new());
1834         self.arena.alloc(expr)
1835     }
1836
1837     pub(super) fn expr_block(
1838         &mut self,
1839         b: &'hir hir::Block<'hir>,
1840         attrs: AttrVec,
1841     ) -> hir::Expr<'hir> {
1842         self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
1843     }
1844
1845     pub(super) fn expr(
1846         &mut self,
1847         span: Span,
1848         kind: hir::ExprKind<'hir>,
1849         attrs: AttrVec,
1850     ) -> hir::Expr<'hir> {
1851         let hir_id = self.next_id();
1852         self.lower_attrs(hir_id, &attrs);
1853         hir::Expr { hir_id, kind, span }
1854     }
1855
1856     fn expr_field(
1857         &mut self,
1858         ident: Ident,
1859         expr: &'hir hir::Expr<'hir>,
1860         span: Span,
1861     ) -> hir::ExprField<'hir> {
1862         hir::ExprField { hir_id: self.next_id(), ident, span, expr, is_shorthand: false }
1863     }
1864
1865     fn arm(&mut self, pat: &'hir hir::Pat<'hir>, expr: &'hir hir::Expr<'hir>) -> hir::Arm<'hir> {
1866         hir::Arm { hir_id: self.next_id(), pat, guard: None, span: expr.span, body: expr }
1867     }
1868 }