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