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