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