expr.rs 55.9 KB
Newer Older
M
Mark Rousskov 已提交
1
use super::{ImplTraitContext, LoweringContext, ParamMode, ParenthesizedGenericArgs};
2

3 4 5
use rustc_ast::ast::*;
use rustc_ast::attr;
use rustc_ast::ptr::P as AstP;
6
use rustc_data_structures::thin_vec::ThinVec;
7
use rustc_errors::struct_span_err;
8 9
use rustc_hir as hir;
use rustc_hir::def::Res;
10 11
use rustc_span::source_map::{respan, DesugaringKind, Span, Spanned};
use rustc_span::symbol::{sym, Symbol};
12

C
Camille GILLOT 已提交
13
impl<'hir> LoweringContext<'_, 'hir> {
C
Camille GILLOT 已提交
14
    fn lower_exprs(&mut self, exprs: &[AstP<Expr>]) -> &'hir [hir::Expr<'hir>] {
C
Camille GILLOT 已提交
15
        self.arena.alloc_from_iter(exprs.iter().map(|x| self.lower_expr_mut(x)))
16 17
    }

C
Camille GILLOT 已提交
18 19 20 21 22
    pub(super) fn lower_expr(&mut self, e: &Expr) -> &'hir hir::Expr<'hir> {
        self.arena.alloc(self.lower_expr_mut(e))
    }

    pub(super) fn lower_expr_mut(&mut self, e: &Expr) -> hir::Expr<'hir> {
V
varkor 已提交
23
        let kind = match e.kind {
C
Camille GILLOT 已提交
24
            ExprKind::Box(ref inner) => hir::ExprKind::Box(self.lower_expr(inner)),
25 26
            ExprKind::Array(ref exprs) => hir::ExprKind::Array(self.lower_exprs(exprs)),
            ExprKind::Repeat(ref expr, ref count) => {
C
Camille GILLOT 已提交
27
                let expr = self.lower_expr(expr);
28 29 30 31 32
                let count = self.lower_anon_const(count);
                hir::ExprKind::Repeat(expr, count)
            }
            ExprKind::Tup(ref elts) => hir::ExprKind::Tup(self.lower_exprs(elts)),
            ExprKind::Call(ref f, ref args) => {
C
Camille GILLOT 已提交
33
                let f = self.lower_expr(f);
34 35 36
                hir::ExprKind::Call(f, self.lower_exprs(args))
            }
            ExprKind::MethodCall(ref seg, ref args) => {
C
Camille GILLOT 已提交
37
                let hir_seg = self.arena.alloc(self.lower_path_segment(
38 39 40 41 42 43 44 45 46 47 48 49 50
                    e.span,
                    seg,
                    ParamMode::Optional,
                    0,
                    ParenthesizedGenericArgs::Err,
                    ImplTraitContext::disallowed(),
                    None,
                ));
                let args = self.lower_exprs(args);
                hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args)
            }
            ExprKind::Binary(binop, ref lhs, ref rhs) => {
                let binop = self.lower_binop(binop);
C
Camille GILLOT 已提交
51 52
                let lhs = self.lower_expr(lhs);
                let rhs = self.lower_expr(rhs);
53 54 55 56
                hir::ExprKind::Binary(binop, lhs, rhs)
            }
            ExprKind::Unary(op, ref ohs) => {
                let op = self.lower_unop(op);
C
Camille GILLOT 已提交
57
                let ohs = self.lower_expr(ohs);
58 59
                hir::ExprKind::Unary(op, ohs)
            }
V
varkor 已提交
60
            ExprKind::Lit(ref l) => hir::ExprKind::Lit(respan(l.span, l.kind.clone())),
61
            ExprKind::Cast(ref expr, ref ty) => {
C
Camille GILLOT 已提交
62
                let expr = self.lower_expr(expr);
C
Camille GILLOT 已提交
63
                let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
C
Camille GILLOT 已提交
64
                hir::ExprKind::Cast(expr, ty)
65 66
            }
            ExprKind::Type(ref expr, ref ty) => {
C
Camille GILLOT 已提交
67
                let expr = self.lower_expr(expr);
C
Camille GILLOT 已提交
68
                let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
C
Camille GILLOT 已提交
69
                hir::ExprKind::Type(expr, ty)
70
            }
71
            ExprKind::AddrOf(k, m, ref ohs) => {
C
Camille GILLOT 已提交
72
                let ohs = self.lower_expr(ohs);
73
                hir::ExprKind::AddrOf(k, m, ohs)
74
            }
75
            ExprKind::Let(ref pat, ref scrutinee) => self.lower_expr_let(e.span, pat, scrutinee),
76
            ExprKind::If(ref cond, ref then, ref else_opt) => {
77
                self.lower_expr_if(e.span, cond, then, else_opt.as_deref())
78 79
            }
            ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
80
                this.lower_expr_while_in_loop_scope(e.span, cond, body, opt_label)
81 82
            }),
            ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
83
                hir::ExprKind::Loop(this.lower_block(body, false), opt_label, hir::LoopSource::Loop)
84
            }),
85
            ExprKind::TryBlock(ref body) => self.lower_expr_try_block(body),
86
            ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
C
Camille GILLOT 已提交
87
                self.lower_expr(expr),
C
Camille GILLOT 已提交
88
                self.arena.alloc_from_iter(arms.iter().map(|x| self.lower_arm(x))),
89 90
                hir::MatchSource::Normal,
            ),
M
Mark Rousskov 已提交
91 92 93 94 95 96 97 98
            ExprKind::Async(capture_clause, closure_node_id, ref block) => self.make_async_expr(
                capture_clause,
                closure_node_id,
                None,
                block.span,
                hir::AsyncGeneratorKind::Block,
                |this| this.with_new_scopes(|this| this.lower_block_expr(block)),
            ),
99
            ExprKind::Await(ref expr) => self.lower_expr_await(e.span, expr),
100
            ExprKind::Closure(
M
Mark Rousskov 已提交
101 102 103 104 105 106 107
                capture_clause,
                asyncness,
                movability,
                ref decl,
                ref body,
                fn_decl_span,
            ) => {
108
                if let Async::Yes { closure_id, .. } = asyncness {
M
Mark Rousskov 已提交
109 110 111 112 113 114 115 116 117 118
                    self.lower_expr_async_closure(
                        capture_clause,
                        closure_id,
                        decl,
                        body,
                        fn_decl_span,
                    )
                } else {
                    self.lower_expr_closure(capture_clause, movability, decl, body, fn_decl_span)
                }
119
            }
120 121 122
            ExprKind::Block(ref blk, opt_label) => {
                hir::ExprKind::Block(self.lower_block(blk, opt_label.is_some()), opt_label)
            }
C
Camille GILLOT 已提交
123 124 125
            ExprKind::Assign(ref el, ref er, span) => {
                hir::ExprKind::Assign(self.lower_expr(el), self.lower_expr(er), span)
            }
126 127
            ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
                self.lower_binop(op),
C
Camille GILLOT 已提交
128 129
                self.lower_expr(el),
                self.lower_expr(er),
130
            ),
C
Camille GILLOT 已提交
131 132 133
            ExprKind::Field(ref el, ident) => hir::ExprKind::Field(self.lower_expr(el), ident),
            ExprKind::Index(ref el, ref er) => {
                hir::ExprKind::Index(self.lower_expr(el), self.lower_expr(er))
134 135
            }
            ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
136
                self.lower_expr_range_closed(e.span, e1, e2)
137 138
            }
            ExprKind::Range(ref e1, ref e2, lims) => {
139
                self.lower_expr_range(e.span, e1.as_deref(), e2.as_deref(), lims)
140 141 142 143 144 145 146 147 148 149 150
            }
            ExprKind::Path(ref qself, ref path) => {
                let qpath = self.lower_qpath(
                    e.id,
                    qself,
                    path,
                    ParamMode::Optional,
                    ImplTraitContext::disallowed(),
                );
                hir::ExprKind::Path(qpath)
            }
C
Camille GILLOT 已提交
151
            ExprKind::Break(opt_label, ref opt_expr) => {
C
Camille GILLOT 已提交
152
                let opt_expr = opt_expr.as_ref().map(|x| self.lower_expr(x));
C
Camille GILLOT 已提交
153 154
                hir::ExprKind::Break(self.lower_jump_destination(e.id, opt_label), opt_expr)
            }
155
            ExprKind::Continue(opt_label) => {
156
                hir::ExprKind::Continue(self.lower_jump_destination(e.id, opt_label))
157
            }
C
Camille GILLOT 已提交
158
            ExprKind::Ret(ref e) => {
C
Camille GILLOT 已提交
159
                let e = e.as_ref().map(|x| self.lower_expr(x));
C
Camille GILLOT 已提交
160 161
                hir::ExprKind::Ret(e)
            }
A
Amanieu d'Antras 已提交
162
            ExprKind::LlvmInlineAsm(ref asm) => self.lower_expr_asm(asm),
C
Camille GILLOT 已提交
163
            ExprKind::Struct(ref path, ref fields, ref maybe_expr) => {
C
Camille GILLOT 已提交
164
                let maybe_expr = maybe_expr.as_ref().map(|x| self.lower_expr(x));
C
Camille GILLOT 已提交
165 166 167 168 169 170 171 172 173 174 175 176
                hir::ExprKind::Struct(
                    self.arena.alloc(self.lower_qpath(
                        e.id,
                        &None,
                        path,
                        ParamMode::Optional,
                        ImplTraitContext::disallowed(),
                    )),
                    self.arena.alloc_from_iter(fields.iter().map(|x| self.lower_field(x))),
                    maybe_expr,
                )
            }
177
            ExprKind::Paren(ref ex) => {
C
Camille GILLOT 已提交
178
                let mut ex = self.lower_expr_mut(ex);
179 180 181 182 183 184 185 186 187 188 189
                // Include parens in span, but only if it is a super-span.
                if e.span.contains(ex.span) {
                    ex.span = e.span;
                }
                // Merge attributes into the inner expression.
                let mut attrs = e.attrs.clone();
                attrs.extend::<Vec<_>>(ex.attrs.into());
                ex.attrs = attrs;
                return ex;
            }

190
            ExprKind::Yield(ref opt_expr) => self.lower_expr_yield(e.span, opt_expr.as_deref()),
191 192 193 194 195 196

            ExprKind::Err => hir::ExprKind::Err,

            // Desugar `ExprForLoop`
            // from: `[opt_ident]: for <pat> in <head> <body>`
            ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
197 198 199
                return self.lower_expr_for(e, pat, head, body, opt_label);
            }
            ExprKind::Try(ref sub_expr) => self.lower_expr_try(e.span, sub_expr),
200
            ExprKind::MacCall(_) => panic!("Shouldn't exist here"),
201
        };
202

Y
Yuki Okushi 已提交
203 204 205 206 207 208
        hir::Expr {
            hir_id: self.lower_node_id(e.id),
            kind,
            span: e.span,
            attrs: e.attrs.iter().map(|a| self.lower_attr(a)).collect::<Vec<_>>().into(),
        }
209
    }
210

211 212
    fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
        match u {
213 214 215
            UnOp::Deref => hir::UnOp::UnDeref,
            UnOp::Not => hir::UnOp::UnNot,
            UnOp::Neg => hir::UnOp::UnNeg,
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
        }
    }

    fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
        Spanned {
            node: match b.node {
                BinOpKind::Add => hir::BinOpKind::Add,
                BinOpKind::Sub => hir::BinOpKind::Sub,
                BinOpKind::Mul => hir::BinOpKind::Mul,
                BinOpKind::Div => hir::BinOpKind::Div,
                BinOpKind::Rem => hir::BinOpKind::Rem,
                BinOpKind::And => hir::BinOpKind::And,
                BinOpKind::Or => hir::BinOpKind::Or,
                BinOpKind::BitXor => hir::BinOpKind::BitXor,
                BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
                BinOpKind::BitOr => hir::BinOpKind::BitOr,
                BinOpKind::Shl => hir::BinOpKind::Shl,
                BinOpKind::Shr => hir::BinOpKind::Shr,
                BinOpKind::Eq => hir::BinOpKind::Eq,
                BinOpKind::Lt => hir::BinOpKind::Lt,
                BinOpKind::Le => hir::BinOpKind::Le,
                BinOpKind::Ne => hir::BinOpKind::Ne,
                BinOpKind::Ge => hir::BinOpKind::Ge,
                BinOpKind::Gt => hir::BinOpKind::Gt,
            },
            span: b.span,
        }
    }

245
    /// Emit an error and lower `ast::ExprKind::Let(pat, scrutinee)` into:
246 247 248
    /// ```rust
    /// match scrutinee { pats => true, _ => false }
    /// ```
C
Camille GILLOT 已提交
249
    fn lower_expr_let(&mut self, span: Span, pat: &Pat, scrutinee: &Expr) -> hir::ExprKind<'hir> {
250
        // If we got here, the `let` expression is not allowed.
251 252 253 254 255 256 257

        if self.sess.opts.unstable_features.is_nightly_build() {
            self.sess
                .struct_span_err(span, "`let` expressions are not supported here")
                .note("only supported directly in conditions of `if`- and `while`-expressions")
                .note("as well as when nested within `&&` and parenthesis in those conditions")
                .emit();
M
Mark Rousskov 已提交
258
        } else {
259 260 261 262 263
            self.sess
                .struct_span_err(span, "expected expression, found statement (`let`)")
                .note("variable declaration using `let` is a statement")
                .emit();
        }
264 265 266

        // For better recovery, we emit:
        // ```
267
        // match scrutinee { pat => true, _ => false }
268 269 270
        // ```
        // While this doesn't fully match the user's intent, it has key advantages:
        // 1. We can avoid using `abort_if_errors`.
271 272
        // 2. We can typeck both `pat` and `scrutinee`.
        // 3. `pat` is allowed to be refutable.
273 274 275
        // 4. The return type of the block is `bool` which seems like what the user wanted.
        let scrutinee = self.lower_expr(scrutinee);
        let then_arm = {
276
            let pat = self.lower_pat(pat);
277
            let expr = self.expr_bool(span, true);
C
Camille GILLOT 已提交
278
            self.arm(pat, expr)
279 280
        };
        let else_arm = {
281
            let pat = self.pat_wild(span);
282
            let expr = self.expr_bool(span, false);
C
Camille GILLOT 已提交
283
            self.arm(pat, expr)
284 285
        };
        hir::ExprKind::Match(
C
Camille GILLOT 已提交
286
            scrutinee,
C
Camille GILLOT 已提交
287
            arena_vec![self; then_arm, else_arm],
288 289 290 291
            hir::MatchSource::Normal,
        )
    }

292 293 294 295 296 297
    fn lower_expr_if(
        &mut self,
        span: Span,
        cond: &Expr,
        then: &Block,
        else_opt: Option<&Expr>,
C
Camille GILLOT 已提交
298
    ) -> hir::ExprKind<'hir> {
299 300 301 302 303 304 305 306
        // FIXME(#53667): handle lowering of && and parens.

        // `_ => else_block` where `else_block` is `{}` if there's `None`:
        let else_pat = self.pat_wild(span);
        let (else_expr, contains_else_clause) = match else_opt {
            None => (self.expr_block_empty(span), false),
            Some(els) => (self.lower_expr(els), true),
        };
C
Camille GILLOT 已提交
307
        let else_arm = self.arm(else_pat, else_expr);
308 309

        // Handle then + scrutinee:
310
        let then_expr = self.lower_block_expr(then);
V
varkor 已提交
311
        let (then_pat, scrutinee, desugar) = match cond.kind {
312
            // `<pat> => <then>`:
313
            ExprKind::Let(ref pat, ref scrutinee) => {
314
                let scrutinee = self.lower_expr(scrutinee);
315
                let pat = self.lower_pat(pat);
316
                (pat, scrutinee, hir::MatchSource::IfLetDesugar { contains_else_clause })
317 318 319 320 321
            }
            // `true => <then>`:
            _ => {
                // Lower condition:
                let cond = self.lower_expr(cond);
M
Mark Rousskov 已提交
322 323
                let span_block =
                    self.mark_span_with_reason(DesugaringKind::CondTemporary, cond.span, None);
324 325 326
                // Wrap in a construct equivalent to `{ let _t = $cond; _t }`
                // to preserve drop semantics since `if cond { ... }` does not
                // let temporaries live outside of `cond`.
C
Camille GILLOT 已提交
327
                let cond = self.expr_drop_temps(span_block, cond, ThinVec::new());
328
                let pat = self.pat_bool(span, true);
329
                (pat, cond, hir::MatchSource::IfDesugar { contains_else_clause })
330 331
            }
        };
C
Camille GILLOT 已提交
332
        let then_arm = self.arm(then_pat, self.arena.alloc(then_expr));
333

C
Camille GILLOT 已提交
334
        hir::ExprKind::Match(scrutinee, arena_vec![self; then_arm, else_arm], desugar)
335 336
    }

337 338 339 340 341
    fn lower_expr_while_in_loop_scope(
        &mut self,
        span: Span,
        cond: &Expr,
        body: &Block,
M
Mark Rousskov 已提交
342
        opt_label: Option<Label>,
C
Camille GILLOT 已提交
343
    ) -> hir::ExprKind<'hir> {
344 345 346 347 348 349 350 351 352
        // FIXME(#53667): handle lowering of && and parens.

        // Note that the block AND the condition are evaluated in the loop scope.
        // This is done to allow `break` from inside the condition of the loop.

        // `_ => break`:
        let else_arm = {
            let else_pat = self.pat_wild(span);
            let else_expr = self.expr_break(span, ThinVec::new());
353
            self.arm(else_pat, else_expr)
354 355 356
        };

        // Handle then + scrutinee:
357
        let then_expr = self.lower_block_expr(body);
V
varkor 已提交
358
        let (then_pat, scrutinee, desugar, source) = match cond.kind {
359
            ExprKind::Let(ref pat, ref scrutinee) => {
360 361 362 363 364 365 366 367 368
                // to:
                //
                //   [opt_ident]: loop {
                //     match <sub_expr> {
                //       <pat> => <body>,
                //       _ => break
                //     }
                //   }
                let scrutinee = self.with_loop_condition_scope(|t| t.lower_expr(scrutinee));
369
                let pat = self.lower_pat(pat);
370
                (pat, scrutinee, hir::MatchSource::WhileLetDesugar, hir::LoopSource::WhileLet)
371 372 373 374 375 376
            }
            _ => {
                // We desugar: `'label: while $cond $body` into:
                //
                // ```
                // 'label: loop {
377
                //     match drop-temps { $cond } {
378 379 380 381 382 383 384 385
                //         true => $body,
                //         _ => break,
                //     }
                // }
                // ```

                // Lower condition:
                let cond = self.with_loop_condition_scope(|this| this.lower_expr(cond));
M
Mark Rousskov 已提交
386 387
                let span_block =
                    self.mark_span_with_reason(DesugaringKind::CondTemporary, cond.span, None);
388 389 390
                // Wrap in a construct equivalent to `{ let _t = $cond; _t }`
                // to preserve drop semantics since `while cond { ... }` does not
                // let temporaries live outside of `cond`.
C
Camille GILLOT 已提交
391
                let cond = self.expr_drop_temps(span_block, cond, ThinVec::new());
392
                // `true => <then>`:
393
                let pat = self.pat_bool(span, true);
394
                (pat, cond, hir::MatchSource::WhileDesugar, hir::LoopSource::While)
395 396
            }
        };
C
Camille GILLOT 已提交
397
        let then_arm = self.arm(then_pat, self.arena.alloc(then_expr));
398 399

        // `match <scrutinee> { ... }`
C
Camille GILLOT 已提交
400 401
        let match_expr = self.expr_match(
            scrutinee.span,
C
Camille GILLOT 已提交
402
            scrutinee,
C
Camille GILLOT 已提交
403 404 405
            arena_vec![self; then_arm, else_arm],
            desugar,
        );
406 407

        // `[opt_ident]: loop { ... }`
408
        hir::ExprKind::Loop(self.block_expr(self.arena.alloc(match_expr)), opt_label, source)
409 410
    }

A
Alex Zatelepin 已提交
411 412 413
    /// Desugar `try { <stmts>; <expr> }` into `{ <stmts>; ::std::ops::Try::from_ok(<expr>) }`,
    /// `try { <stmts>; }` into `{ <stmts>; ::std::ops::Try::from_ok(()) }`
    /// and save the block id to use it as a break target for desugaring of the `?` operator.
C
Camille GILLOT 已提交
414
    fn lower_expr_try_block(&mut self, body: &Block) -> hir::ExprKind<'hir> {
415
        self.with_catch_scope(body.id, |this| {
C
Camille GILLOT 已提交
416
            let mut block = this.lower_block_noalloc(body, true);
417

A
Alex Zatelepin 已提交
418
            let try_span = this.mark_span_with_reason(
419
                DesugaringKind::TryBlock,
A
Alex Zatelepin 已提交
420
                body.span,
421 422
                this.allow_try_trait.clone(),
            );
423

A
Alex Zatelepin 已提交
424
            // Final expression of the block (if present) or `()` with span at the end of block
C
Camille GILLOT 已提交
425 426 427 428
            let tail_expr = block
                .expr
                .take()
                .unwrap_or_else(|| this.expr_unit(this.sess.source_map().end_point(try_span)));
A
Alex Zatelepin 已提交
429

M
Mark Rousskov 已提交
430 431
            let ok_wrapped_span =
                this.mark_span_with_reason(DesugaringKind::TryBlock, tail_expr.span, None);
432

A
Alex Zatelepin 已提交
433
            // `::std::ops::Try::from_ok($tail_expr)`
434
            block.expr = Some(this.wrap_in_try_constructor(
M
Mark Rousskov 已提交
435 436 437 438 439
                sym::from_ok,
                try_span,
                tail_expr,
                ok_wrapped_span,
            ));
440

C
Camille GILLOT 已提交
441
            hir::ExprKind::Block(this.arena.alloc(block), None)
442 443 444
        })
    }

445 446 447
    fn wrap_in_try_constructor(
        &mut self,
        method: Symbol,
448
        method_span: Span,
C
Camille GILLOT 已提交
449
        expr: &'hir hir::Expr<'hir>,
450
        overall_span: Span,
C
Camille GILLOT 已提交
451
    ) -> &'hir hir::Expr<'hir> {
452
        let path = &[sym::ops, sym::Try, method];
C
Camille GILLOT 已提交
453 454
        let constructor =
            self.arena.alloc(self.expr_std_path(method_span, path, None, ThinVec::new()));
C
Camille GILLOT 已提交
455
        self.expr_call(overall_span, constructor, std::slice::from_ref(expr))
456 457
    }

C
Camille GILLOT 已提交
458
    fn lower_arm(&mut self, arm: &Arm) -> hir::Arm<'hir> {
459 460
        hir::Arm {
            hir_id: self.next_id(),
C
Camille GILLOT 已提交
461
            attrs: self.lower_attrs(&arm.attrs),
462
            pat: self.lower_pat(&arm.pat),
463
            guard: match arm.guard {
C
Camille GILLOT 已提交
464
                Some(ref x) => Some(hir::Guard::If(self.lower_expr(x))),
465 466
                _ => None,
            },
C
Camille GILLOT 已提交
467
            body: self.lower_expr(&arm.body),
468 469 470 471
            span: arm.span,
        }
    }

472 473 474 475 476 477 478 479 480
    /// Lower an `async` construct to a generator that is then wrapped so it implements `Future`.
    ///
    /// This results in:
    ///
    /// ```text
    /// std::future::from_generator(static move? |_task_context| -> <ret_ty> {
    ///     <body>
    /// })
    /// ```
481 482 483 484 485 486
    pub(super) fn make_async_expr(
        &mut self,
        capture_clause: CaptureBy,
        closure_node_id: NodeId,
        ret_ty: Option<AstP<Ty>>,
        span: Span,
487
        async_gen_kind: hir::AsyncGeneratorKind,
C
Camille GILLOT 已提交
488 489
        body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
    ) -> hir::ExprKind<'hir> {
490
        let output = match ret_ty {
491 492
            Some(ty) => hir::FnRetTy::Return(self.lower_ty(&ty, ImplTraitContext::disallowed())),
            None => hir::FnRetTy::DefaultReturn(span),
493
        };
494

495 496 497
        // Resume argument type. We let the compiler infer this to simplify the lowering. It is
        // fully constrained by `future::from_generator`.
        let input_ty = hir::Ty { hir_id: self.next_id(), kind: hir::TyKind::Infer, span };
498

499 500 501
        // The closure/generator `FnDecl` takes a single (resume) argument of type `input_ty`.
        let decl = self.arena.alloc(hir::FnDecl {
            inputs: arena_vec![self; input_ty],
502
            output,
503 504 505 506 507 508 509 510 511 512 513 514 515 516
            c_variadic: false,
            implicit_self: hir::ImplicitSelfKind::None,
        });

        // Lower the argument pattern/ident. The ident is used again in the `.await` lowering.
        let (pat, task_context_hid) = self.pat_ident_binding_mode(
            span,
            Ident::with_dummy_span(sym::_task_context),
            hir::BindingAnnotation::Mutable,
        );
        let param = hir::Param { attrs: &[], hir_id: self.next_id(), pat, span };
        let params = arena_vec![self; param];

        let body_id = self.lower_body(move |this| {
517
            this.generator_kind = Some(hir::GeneratorKind::Async(async_gen_kind));
518 519 520 521 522

            let old_ctx = this.task_context;
            this.task_context = Some(task_context_hid);
            let res = body(this);
            this.task_context = old_ctx;
523
            (params, res)
524 525
        });

526
        // `static |_task_context| -> <ret_ty> { body }`:
V
varkor 已提交
527
        let generator_kind = hir::ExprKind::Closure(
528 529 530 531
            capture_clause,
            decl,
            body_id,
            span,
M
Mark Rousskov 已提交
532
            Some(hir::Movability::Static),
533 534 535
        );
        let generator = hir::Expr {
            hir_id: self.lower_node_id(closure_node_id),
V
varkor 已提交
536
            kind: generator_kind,
537 538 539 540 541
            span,
            attrs: ThinVec::new(),
        };

        // `future::from_generator`:
M
Mark Rousskov 已提交
542 543
        let unstable_span =
            self.mark_span_with_reason(DesugaringKind::Async, span, self.allow_gen_future.clone());
544 545 546 547
        let gen_future = self.expr_std_path(
            unstable_span,
            &[sym::future, sym::from_generator],
            None,
M
Mark Rousskov 已提交
548
            ThinVec::new(),
549 550 551
        );

        // `future::from_generator(generator)`:
C
Camille GILLOT 已提交
552
        hir::ExprKind::Call(self.arena.alloc(gen_future), arena_vec![self; generator])
553 554
    }

555 556
    /// Desugar `<expr>.await` into:
    /// ```rust
557
    /// match <expr> {
558
    ///     mut pinned => loop {
559 560 561 562
    ///         match unsafe { ::std::future::poll_with_context(
    ///             <::std::pin::Pin>::new_unchecked(&mut pinned),
    ///             task_context,
    ///         ) } {
563
    ///             ::std::task::Poll::Ready(result) => break result,
564
    ///             ::std::task::Poll::Pending => {}
565
    ///         }
566
    ///         task_context = yield ();
567 568 569
    ///     }
    /// }
    /// ```
C
Camille GILLOT 已提交
570
    fn lower_expr_await(&mut self, await_span: Span, expr: &Expr) -> hir::ExprKind<'hir> {
571
        match self.generator_kind {
M
Mark Rousskov 已提交
572 573
            Some(hir::GeneratorKind::Async(_)) => {}
            Some(hir::GeneratorKind::Gen) | None => {
574 575 576 577 578 579 580 581 582 583 584 585 586
                let mut err = struct_span_err!(
                    self.sess,
                    await_span,
                    E0728,
                    "`await` is only allowed inside `async` functions and blocks"
                );
                err.span_label(await_span, "only allowed inside `async` functions and blocks");
                if let Some(item_sp) = self.current_item {
                    err.span_label(item_sp, "this is not `async`");
                }
                err.emit();
            }
        }
M
Mark Rousskov 已提交
587
        let span = self.mark_span_with_reason(DesugaringKind::Await, await_span, None);
588 589 590 591 592
        let gen_future_span = self.mark_span_with_reason(
            DesugaringKind::Await,
            await_span,
            self.allow_gen_future.clone(),
        );
593
        let expr = self.lower_expr(expr);
594

595
        let pinned_ident = Ident::with_dummy_span(sym::pinned);
M
Mark Rousskov 已提交
596 597
        let (pinned_pat, pinned_pat_hid) =
            self.pat_ident_binding_mode(span, pinned_ident, hir::BindingAnnotation::Mutable);
598

599 600 601 602 603 604 605 606
        let task_context_ident = Ident::with_dummy_span(sym::_task_context);

        // unsafe {
        //     ::std::future::poll_with_context(
        //         ::std::pin::Pin::new_unchecked(&mut pinned),
        //         task_context,
        //     )
        // }
607
        let poll_expr = {
C
Camille GILLOT 已提交
608
            let pinned = self.expr_ident(span, pinned_ident, pinned_pat_hid);
609
            let ref_mut_pinned = self.expr_mut_addr_of(span, pinned);
610 611 612 613 614 615
            let task_context = if let Some(task_context_hid) = self.task_context {
                self.expr_ident_mut(span, task_context_ident, task_context_hid)
            } else {
                // Use of `await` outside of an async context, we cannot use `task_context` here.
                self.expr_err(span)
            };
616 617 618 619 620 621
            let pin_ty_id = self.next_id();
            let new_unchecked_expr_kind = self.expr_call_std_assoc_fn(
                pin_ty_id,
                span,
                &[sym::pin, sym::Pin],
                "new_unchecked",
C
Camille GILLOT 已提交
622
                arena_vec![self; ref_mut_pinned],
623
            );
624 625
            let new_unchecked = self.expr(span, new_unchecked_expr_kind, ThinVec::new());
            let call = self.expr_call_std_path(
626
                gen_future_span,
627 628 629 630
                &[sym::future, sym::poll_with_context],
                arena_vec![self; new_unchecked, task_context],
            );
            self.arena.alloc(self.expr_unsafe(call))
631 632 633
        };

        // `::std::task::Poll::Ready(result) => break result`
M
Mark Rousskov 已提交
634
        let loop_node_id = self.resolver.next_node_id();
635 636
        let loop_hir_id = self.lower_node_id(loop_node_id);
        let ready_arm = {
637
            let x_ident = Ident::with_dummy_span(sym::result);
638
            let (x_pat, x_pat_hid) = self.pat_ident(span, x_ident);
C
Camille GILLOT 已提交
639
            let x_expr = self.expr_ident(span, x_ident, x_pat_hid);
C
Camille GILLOT 已提交
640 641 642 643 644 645
            let ready_pat = self.pat_std_enum(
                span,
                &[sym::task, sym::Poll, sym::Ready],
                arena_vec![self; x_pat],
            );
            let break_x = self.with_loop_scope(loop_node_id, move |this| {
M
Mark Rousskov 已提交
646 647
                let expr_break =
                    hir::ExprKind::Break(this.lower_loop_destination(None), Some(x_expr));
C
Camille GILLOT 已提交
648
                this.arena.alloc(this.expr(await_span, expr_break, ThinVec::new()))
649
            });
650
            self.arm(ready_pat, break_x)
651 652 653 654
        };

        // `::std::task::Poll::Pending => {}`
        let pending_arm = {
C
Camille GILLOT 已提交
655
            let pending_pat = self.pat_std_enum(span, &[sym::task, sym::Poll, sym::Pending], &[]);
C
Camille GILLOT 已提交
656
            let empty_block = self.expr_block_empty(span);
657
            self.arm(pending_pat, empty_block)
658 659
        };

660
        let inner_match_stmt = {
661 662 663
            let match_expr = self.expr_match(
                span,
                poll_expr,
C
Camille GILLOT 已提交
664
                arena_vec![self; ready_arm, pending_arm],
665 666 667 668 669
                hir::MatchSource::AwaitDesugar,
            );
            self.stmt_expr(span, match_expr)
        };

670
        // task_context = yield ();
671 672 673 674
        let yield_stmt = {
            let unit = self.expr_unit(span);
            let yield_expr = self.expr(
                span,
675
                hir::ExprKind::Yield(unit, hir::YieldSource::Await { expr: Some(expr.hir_id) }),
676 677
                ThinVec::new(),
            );
678 679 680 681
            let yield_expr = self.arena.alloc(yield_expr);

            if let Some(task_context_hid) = self.task_context {
                let lhs = self.expr_ident(span, task_context_ident, task_context_hid);
J
Format  
Jonas Schievink 已提交
682 683
                let assign =
                    self.expr(span, hir::ExprKind::Assign(lhs, yield_expr, span), AttrVec::new());
684 685 686 687 688 689
                self.stmt_expr(span, assign)
            } else {
                // Use of `await` outside of an async context. Return `yield_expr` so that we can
                // proceed with type checking.
                self.stmt(span, hir::StmtKind::Semi(yield_expr))
            }
690 691
        };

J
Format  
Jonas Schievink 已提交
692
        let loop_block = self.block_all(span, arena_vec![self; inner_match_stmt, yield_stmt], None);
693

694
        // loop { .. }
C
Camille GILLOT 已提交
695
        let loop_expr = self.arena.alloc(hir::Expr {
696
            hir_id: loop_hir_id,
M
Mark Rousskov 已提交
697
            kind: hir::ExprKind::Loop(loop_block, None, hir::LoopSource::Loop),
698 699 700 701
            span,
            attrs: ThinVec::new(),
        });

702
        // mut pinned => loop { ... }
703
        let pinned_arm = self.arm(pinned_pat, loop_expr);
704

705
        // match <expr> {
706 707
        //     mut pinned => loop { .. }
        // }
708
        hir::ExprKind::Match(expr, arena_vec![self; pinned_arm], hir::MatchSource::AwaitDesugar)
709 710
    }

711 712 713 714 715 716 717
    fn lower_expr_closure(
        &mut self,
        capture_clause: CaptureBy,
        movability: Movability,
        decl: &FnDecl,
        body: &Expr,
        fn_decl_span: Span,
C
Camille GILLOT 已提交
718
    ) -> hir::ExprKind<'hir> {
719 720 721
        // Lower outside new scope to preserve `is_in_loop_condition`.
        let fn_decl = self.lower_fn_decl(decl, None, false, None);

C
Camille GILLOT 已提交
722
        self.with_new_scopes(move |this| {
723
            let prev = this.current_item;
724 725 726
            this.current_item = Some(fn_decl_span);
            let mut generator_kind = None;
            let body_id = this.lower_fn_body(decl, |this| {
C
Camille GILLOT 已提交
727
                let e = this.lower_expr_mut(body);
728 729 730
                generator_kind = this.generator_kind;
                e
            });
M
Mark Rousskov 已提交
731 732
            let generator_option =
                this.generator_movability_for_fn(&decl, fn_decl_span, generator_kind, movability);
733
            this.current_item = prev;
M
Mark Rousskov 已提交
734
            hir::ExprKind::Closure(capture_clause, fn_decl, body_id, fn_decl_span, generator_option)
735 736 737
        })
    }

738 739
    fn generator_movability_for_fn(
        &mut self,
740
        decl: &FnDecl,
741 742 743
        fn_decl_span: Span,
        generator_kind: Option<hir::GeneratorKind>,
        movability: Movability,
744
    ) -> Option<hir::Movability> {
745
        match generator_kind {
M
Mark Rousskov 已提交
746
            Some(hir::GeneratorKind::Gen) => {
747
                if decl.inputs.len() > 1 {
748
                    struct_span_err!(
749 750 751
                        self.sess,
                        fn_decl_span,
                        E0628,
752
                        "too many parameters for a generator (expected 0 or 1 parameters)"
753 754
                    )
                    .emit();
755
                }
756
                Some(movability)
M
Mark Rousskov 已提交
757
            }
758
            Some(hir::GeneratorKind::Async(_)) => {
M
Mazdak Farrokhzad 已提交
759
                panic!("non-`async` closure body turned `async` during lowering");
M
Mark Rousskov 已提交
760
            }
761 762
            None => {
                if movability == Movability::Static {
763 764
                    struct_span_err!(self.sess, fn_decl_span, E0697, "closures cannot be static")
                        .emit();
765 766
                }
                None
M
Mark Rousskov 已提交
767
            }
768 769 770
        }
    }

771 772 773 774 775 776 777
    fn lower_expr_async_closure(
        &mut self,
        capture_clause: CaptureBy,
        closure_id: NodeId,
        decl: &FnDecl,
        body: &Expr,
        fn_decl_span: Span,
C
Camille GILLOT 已提交
778
    ) -> hir::ExprKind<'hir> {
M
Mark Rousskov 已提交
779
        let outer_decl =
780
            FnDecl { inputs: decl.inputs.clone(), output: FnRetTy::Default(fn_decl_span) };
781 782 783 784 785
        // We need to lower the declaration outside the new scope, because we
        // have to conserve the state of being inside a loop condition for the
        // closure argument types.
        let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);

C
Camille GILLOT 已提交
786
        self.with_new_scopes(move |this| {
787 788 789 790 791 792
            // FIXME(cramertj): allow `async` non-`move` closures with arguments.
            if capture_clause == CaptureBy::Ref && !decl.inputs.is_empty() {
                struct_span_err!(
                    this.sess,
                    fn_decl_span,
                    E0708,
793
                    "`async` non-`move` closures with parameters are not currently supported",
794 795 796
                )
                .help(
                    "consider using `let` statements to manually capture \
M
Mark Rousskov 已提交
797
                    variables by reference before entering an `async move` closure",
798 799 800 801 802 803 804
                )
                .emit();
            }

            // Transform `async |x: u8| -> X { ... }` into
            // `|x: u8| future_from_generator(|| -> X { ... })`.
            let body_id = this.lower_fn_body(&outer_decl, |this| {
M
Mark Rousskov 已提交
805
                let async_ret_ty =
806
                    if let FnRetTy::Ty(ty) = &decl.output { Some(ty.clone()) } else { None };
807
                let async_body = this.make_async_expr(
N
Niko Matsakis 已提交
808 809 810 811 812
                    capture_clause,
                    closure_id,
                    async_ret_ty,
                    body.span,
                    hir::AsyncGeneratorKind::Closure,
C
Camille GILLOT 已提交
813
                    |this| this.with_new_scopes(|this| this.lower_expr_mut(body)),
814 815 816
                );
                this.expr(fn_decl_span, async_body, ThinVec::new())
            });
M
Mark Rousskov 已提交
817
            hir::ExprKind::Closure(capture_clause, fn_decl, body_id, fn_decl_span, None)
818 819 820
        })
    }

821
    /// Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`.
C
Camille GILLOT 已提交
822
    fn lower_expr_range_closed(&mut self, span: Span, e1: &Expr, e2: &Expr) -> hir::ExprKind<'hir> {
823
        let id = self.next_id();
C
Camille GILLOT 已提交
824 825
        let e1 = self.lower_expr_mut(e1);
        let e2 = self.lower_expr_mut(e2);
826 827 828 829 830
        self.expr_call_std_assoc_fn(
            id,
            span,
            &[sym::ops, sym::RangeInclusive],
            "new",
C
Camille GILLOT 已提交
831
            arena_vec![self; e1, e2],
832 833 834
        )
    }

835 836 837 838 839 840
    fn lower_expr_range(
        &mut self,
        span: Span,
        e1: Option<&Expr>,
        e2: Option<&Expr>,
        lims: RangeLimits,
C
Camille GILLOT 已提交
841
    ) -> hir::ExprKind<'hir> {
842
        use rustc_ast::ast::RangeLimits::*;
843 844 845 846 847 848 849 850

        let path = match (e1, e2, lims) {
            (None, None, HalfOpen) => sym::RangeFull,
            (Some(..), None, HalfOpen) => sym::RangeFrom,
            (None, Some(..), HalfOpen) => sym::RangeTo,
            (Some(..), Some(..), HalfOpen) => sym::Range,
            (None, Some(..), Closed) => sym::RangeToInclusive,
            (Some(..), Some(..), Closed) => unreachable!(),
M
Mark Rousskov 已提交
851 852 853
            (_, None, Closed) => {
                self.diagnostic().span_fatal(span, "inclusive range with no end").raise()
            }
854 855
        };

C
Camille GILLOT 已提交
856 857
        let fields = self.arena.alloc_from_iter(
            e1.iter().map(|e| ("start", e)).chain(e2.iter().map(|e| ("end", e))).map(|(s, e)| {
C
Camille GILLOT 已提交
858
                let expr = self.lower_expr(&e);
859 860
                let ident = Ident::new(Symbol::intern(s), e.span);
                self.field(ident, expr, e.span)
C
Camille GILLOT 已提交
861 862
            }),
        );
863 864 865 866

        let is_unit = fields.is_empty();
        let struct_path = [sym::ops, path];
        let struct_path = self.std_path(span, &struct_path, None, is_unit);
C
Camille GILLOT 已提交
867
        let struct_path = hir::QPath::Resolved(None, struct_path);
868 869 870 871

        if is_unit {
            hir::ExprKind::Path(struct_path)
        } else {
C
Camille GILLOT 已提交
872
            hir::ExprKind::Struct(self.arena.alloc(struct_path), fields, None)
873 874 875
        }
    }

876 877 878 879 880 881 882 883 884
    fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
        let target_id = match destination {
            Some((id, _)) => {
                if let Some(loop_id) = self.resolver.get_label_res(id) {
                    Ok(self.lower_node_id(loop_id))
                } else {
                    Err(hir::LoopIdError::UnresolvedLabel)
                }
            }
M
Mark Rousskov 已提交
885 886 887 888 889
            None => self
                .loop_scopes
                .last()
                .cloned()
                .map(|id| Ok(self.lower_node_id(id)))
890
                .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope)),
891
        };
892
        hir::Destination { label: destination.map(|(_, label)| label), target_id }
893 894 895 896 897 898
    }

    fn lower_jump_destination(&mut self, id: NodeId, opt_label: Option<Label>) -> hir::Destination {
        if self.is_in_loop_condition && opt_label.is_none() {
            hir::Destination {
                label: None,
899
                target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition),
900 901 902 903 904 905
            }
        } else {
            self.lower_loop_destination(opt_label.map(|label| (id, label)))
        }
    }

M
Mazdak Farrokhzad 已提交
906
    fn with_catch_scope<T>(&mut self, catch_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921
        let len = self.catch_scopes.len();
        self.catch_scopes.push(catch_id);

        let result = f(self);
        assert_eq!(
            len + 1,
            self.catch_scopes.len(),
            "catch scopes should be added and removed in stack order"
        );

        self.catch_scopes.pop().unwrap();

        result
    }

M
Mazdak Farrokhzad 已提交
922
    fn with_loop_scope<T>(&mut self, loop_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
        // We're no longer in the base loop's condition; we're in another loop.
        let was_in_loop_condition = self.is_in_loop_condition;
        self.is_in_loop_condition = false;

        let len = self.loop_scopes.len();
        self.loop_scopes.push(loop_id);

        let result = f(self);
        assert_eq!(
            len + 1,
            self.loop_scopes.len(),
            "loop scopes should be added and removed in stack order"
        );

        self.loop_scopes.pop().unwrap();

        self.is_in_loop_condition = was_in_loop_condition;

        result
    }

M
Mazdak Farrokhzad 已提交
944
    fn with_loop_condition_scope<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
945 946 947 948 949 950 951 952 953 954
        let was_in_loop_condition = self.is_in_loop_condition;
        self.is_in_loop_condition = true;

        let result = f(self);

        self.is_in_loop_condition = was_in_loop_condition;

        result
    }

A
Amanieu d'Antras 已提交
955 956
    fn lower_expr_asm(&mut self, asm: &LlvmInlineAsm) -> hir::ExprKind<'hir> {
        let inner = hir::LlvmInlineAsmInner {
957
            inputs: asm.inputs.iter().map(|&(c, _)| c).collect(),
M
Mark Rousskov 已提交
958 959
            outputs: asm
                .outputs
960
                .iter()
A
Amanieu d'Antras 已提交
961
                .map(|out| hir::LlvmInlineAsmOutput {
962
                    constraint: out.constraint,
963 964 965 966 967
                    is_rw: out.is_rw,
                    is_indirect: out.is_indirect,
                    span: out.expr.span,
                })
                .collect(),
968
            asm: asm.asm,
969
            asm_str_style: asm.asm_str_style,
970
            clobbers: asm.clobbers.clone(),
971 972 973 974
            volatile: asm.volatile,
            alignstack: asm.alignstack,
            dialect: asm.dialect,
        };
A
Amanieu d'Antras 已提交
975
        let hir_asm = hir::LlvmInlineAsm {
M
Mazdak Farrokhzad 已提交
976
            inner,
C
Camille GILLOT 已提交
977 978 979
            inputs_exprs: self.arena.alloc_from_iter(
                asm.inputs.iter().map(|&(_, ref input)| self.lower_expr_mut(input)),
            ),
C
Camille GILLOT 已提交
980 981
            outputs_exprs: self
                .arena
C
Camille GILLOT 已提交
982
                .alloc_from_iter(asm.outputs.iter().map(|out| self.lower_expr_mut(&out.expr))),
M
Mazdak Farrokhzad 已提交
983
        };
A
Amanieu d'Antras 已提交
984
        hir::ExprKind::LlvmInlineAsm(self.arena.alloc(hir_asm))
985 986
    }

C
Camille GILLOT 已提交
987
    fn lower_field(&mut self, f: &Field) -> hir::Field<'hir> {
988 989 990
        hir::Field {
            hir_id: self.next_id(),
            ident: f.ident,
C
Camille GILLOT 已提交
991
            expr: self.lower_expr(&f.expr),
992 993 994 995 996
            span: f.span,
            is_shorthand: f.is_shorthand,
        }
    }

C
Camille GILLOT 已提交
997
    fn lower_expr_yield(&mut self, span: Span, opt_expr: Option<&Expr>) -> hir::ExprKind<'hir> {
998
        match self.generator_kind {
M
Mark Rousskov 已提交
999
            Some(hir::GeneratorKind::Gen) => {}
1000
            Some(hir::GeneratorKind::Async(_)) => {
1001 1002 1003 1004 1005 1006 1007
                struct_span_err!(
                    self.sess,
                    span,
                    E0727,
                    "`async` generators are not yet supported"
                )
                .emit();
1008
                return hir::ExprKind::Err;
M
Mark Rousskov 已提交
1009
            }
1010 1011 1012
            None => self.generator_kind = Some(hir::GeneratorKind::Gen),
        }

M
Mark Rousskov 已提交
1013 1014
        let expr =
            opt_expr.as_ref().map(|x| self.lower_expr(x)).unwrap_or_else(|| self.expr_unit(span));
1015

C
Camille GILLOT 已提交
1016
        hir::ExprKind::Yield(expr, hir::YieldSource::Yield)
1017 1018
    }

1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
    /// Desugar `ExprForLoop` from: `[opt_ident]: for <pat> in <head> <body>` into:
    /// ```rust
    /// {
    ///     let result = match ::std::iter::IntoIterator::into_iter(<head>) {
    ///         mut iter => {
    ///             [opt_ident]: loop {
    ///                 let mut __next;
    ///                 match ::std::iter::Iterator::next(&mut iter) {
    ///                     ::std::option::Option::Some(val) => __next = val,
    ///                     ::std::option::Option::None => break
    ///                 };
    ///                 let <pat> = __next;
    ///                 StmtKind::Expr(<body>);
    ///             }
    ///         }
    ///     };
    ///     result
    /// }
    /// ```
    fn lower_expr_for(
        &mut self,
        e: &Expr,
        pat: &Pat,
        head: &Expr,
        body: &Block,
        opt_label: Option<Label>,
C
Camille GILLOT 已提交
1045
    ) -> hir::Expr<'hir> {
1046
        // expand <head>
C
Camille GILLOT 已提交
1047
        let mut head = self.lower_expr_mut(head);
M
Mark Rousskov 已提交
1048
        let desugared_span = self.mark_span_with_reason(DesugaringKind::ForLoop, head.span, None);
1049
        head.span = desugared_span;
1050

1051
        let iter = Ident::with_dummy_span(sym::iter);
1052

1053
        let next_ident = Ident::with_dummy_span(sym::__next);
1054 1055 1056 1057 1058
        let (next_pat, next_pat_hid) = self.pat_ident_binding_mode(
            desugared_span,
            next_ident,
            hir::BindingAnnotation::Mutable,
        );
1059

1060 1061
        // `::std::option::Option::Some(val) => __next = val`
        let pat_arm = {
1062
            let val_ident = Ident::with_dummy_span(sym::val);
1063
            let (val_pat, val_pat_hid) = self.pat_ident(pat.span, val_ident);
C
Camille GILLOT 已提交
1064 1065
            let val_expr = self.expr_ident(pat.span, val_ident, val_pat_hid);
            let next_expr = self.expr_ident(pat.span, next_ident, next_pat_hid);
C
Camille GILLOT 已提交
1066
            let assign = self.arena.alloc(self.expr(
1067 1068 1069 1070
                pat.span,
                hir::ExprKind::Assign(next_expr, val_expr, pat.span),
                ThinVec::new(),
            ));
1071
            let some_pat = self.pat_some(pat.span, val_pat);
1072
            self.arm(some_pat, assign)
1073
        };
1074

1075 1076 1077 1078 1079
        // `::std::option::Option::None => break`
        let break_arm = {
            let break_expr =
                self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
            let pat = self.pat_none(e.span);
1080
            self.arm(pat, break_expr)
1081
        };
1082

1083
        // `mut iter`
M
Mark Rousskov 已提交
1084 1085
        let (iter_pat, iter_pat_nid) =
            self.pat_ident_binding_mode(desugared_span, iter, hir::BindingAnnotation::Mutable);
1086

1087 1088
        // `match ::std::iter::Iterator::next(&mut iter) { ... }`
        let match_expr = {
C
Camille GILLOT 已提交
1089
            let iter = self.expr_ident(desugared_span, iter, iter_pat_nid);
1090
            let ref_mut_iter = self.expr_mut_addr_of(desugared_span, iter);
1091
            let next_path = &[sym::iter, sym::Iterator, sym::next];
C
Camille GILLOT 已提交
1092 1093
            let next_expr =
                self.expr_call_std_path(desugared_span, next_path, arena_vec![self; ref_mut_iter]);
C
Camille GILLOT 已提交
1094
            let arms = arena_vec![self; pat_arm, break_arm];
1095

1096
            self.expr_match(desugared_span, next_expr, arms, hir::MatchSource::ForLoopDesugar)
1097
        };
1098
        let match_stmt = self.stmt_expr(desugared_span, match_expr);
1099

C
Camille GILLOT 已提交
1100
        let next_expr = self.expr_ident(desugared_span, next_ident, next_pat_hid);
1101

1102 1103 1104 1105 1106 1107 1108 1109
        // `let mut __next`
        let next_let = self.stmt_let_pat(
            ThinVec::new(),
            desugared_span,
            None,
            next_pat,
            hir::LocalSource::ForLoopDesugar,
        );
1110

1111 1112 1113 1114
        // `let <pat> = __next`
        let pat = self.lower_pat(pat);
        let pat_let = self.stmt_let_pat(
            ThinVec::new(),
1115
            desugared_span,
1116 1117 1118 1119
            Some(next_expr),
            pat,
            hir::LocalSource::ForLoopDesugar,
        );
1120

1121 1122 1123 1124
        let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
        let body_expr = self.expr_block(body_block, ThinVec::new());
        let body_stmt = self.stmt_expr(body.span, body_expr);

C
Camille GILLOT 已提交
1125
        let loop_block = self.block_all(
C
Camille GILLOT 已提交
1126 1127 1128
            e.span,
            arena_vec![self; next_let, match_stmt, pat_let, body_stmt],
            None,
C
Camille GILLOT 已提交
1129
        );
1130 1131

        // `[opt_ident]: loop { ... }`
1132
        let kind = hir::ExprKind::Loop(loop_block, opt_label, hir::LoopSource::ForLoop);
C
Camille GILLOT 已提交
1133
        let loop_expr = self.arena.alloc(hir::Expr {
1134
            hir_id: self.lower_node_id(e.id),
V
varkor 已提交
1135
            kind,
1136
            span: e.span,
1137 1138 1139 1140
            attrs: ThinVec::new(),
        });

        // `mut iter => { ... }`
1141
        let iter_arm = self.arm(iter_pat, loop_expr);
1142 1143 1144

        // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
        let into_iter_expr = {
M
Mark Rousskov 已提交
1145
            let into_iter_path = &[sym::iter, sym::IntoIterator, sym::into_iter];
C
Camille GILLOT 已提交
1146
            self.expr_call_std_path(desugared_span, into_iter_path, arena_vec![self; head])
1147 1148
        };

C
Camille GILLOT 已提交
1149
        let match_expr = self.arena.alloc(self.expr_match(
1150
            desugared_span,
1151
            into_iter_expr,
C
Camille GILLOT 已提交
1152
            arena_vec![self; iter_arm],
1153 1154 1155 1156 1157 1158 1159 1160 1161
            hir::MatchSource::ForLoopDesugar,
        ));

        // This is effectively `{ let _result = ...; _result }`.
        // The construct was introduced in #21984 and is necessary to make sure that
        // temporaries in the `head` expression are dropped and do not leak to the
        // surrounding scope of the `match` since the `match` is not a terminating scope.
        //
        // Also, add the attributes to the outer returned expr node.
C
Camille GILLOT 已提交
1162
        self.expr_drop_temps_mut(desugared_span, match_expr, e.attrs.clone())
1163
    }
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175

    /// Desugar `ExprKind::Try` from: `<expr>?` into:
    /// ```rust
    /// match Try::into_result(<expr>) {
    ///     Ok(val) => #[allow(unreachable_code)] val,
    ///     Err(err) => #[allow(unreachable_code)]
    ///                 // If there is an enclosing `try {...}`:
    ///                 break 'catch_target Try::from_error(From::from(err)),
    ///                 // Otherwise:
    ///                 return Try::from_error(From::from(err)),
    /// }
    /// ```
C
Camille GILLOT 已提交
1176
    fn lower_expr_try(&mut self, span: Span, sub_expr: &Expr) -> hir::ExprKind<'hir> {
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
        let unstable_span = self.mark_span_with_reason(
            DesugaringKind::QuestionMark,
            span,
            self.allow_try_trait.clone(),
        );
        let try_span = self.sess.source_map().end_point(span);
        let try_span = self.mark_span_with_reason(
            DesugaringKind::QuestionMark,
            try_span,
            self.allow_try_trait.clone(),
        );

        // `Try::into_result(<expr>)`
        let scrutinee = {
            // expand <expr>
C
Camille GILLOT 已提交
1192
            let sub_expr = self.lower_expr_mut(sub_expr);
1193 1194

            let path = &[sym::ops, sym::Try, sym::into_result];
C
Camille GILLOT 已提交
1195
            self.expr_call_std_path(unstable_span, path, arena_vec![self; sub_expr])
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
        };

        // `#[allow(unreachable_code)]`
        let attr = {
            // `allow(unreachable_code)`
            let allow = {
                let allow_ident = Ident::new(sym::allow, span);
                let uc_ident = Ident::new(sym::unreachable_code, span);
                let uc_nested = attr::mk_nested_word_item(uc_ident);
                attr::mk_list_item(allow_ident, vec![uc_nested])
            };
            attr::mk_attr_outer(allow)
        };
        let attrs = vec![attr];

        // `Ok(val) => #[allow(unreachable_code)] val,`
        let ok_arm = {
1213
            let val_ident = Ident::with_dummy_span(sym::val);
1214
            let (val_pat, val_pat_nid) = self.pat_ident(span, val_ident);
C
Camille GILLOT 已提交
1215
            let val_expr = self.arena.alloc(self.expr_ident_with_attrs(
1216 1217 1218 1219 1220 1221
                span,
                val_ident,
                val_pat_nid,
                ThinVec::from(attrs.clone()),
            ));
            let ok_pat = self.pat_ok(span, val_pat);
1222
            self.arm(ok_pat, val_expr)
1223 1224 1225 1226 1227
        };

        // `Err(err) => #[allow(unreachable_code)]
        //              return Try::from_error(From::from(err)),`
        let err_arm = {
1228
            let err_ident = Ident::with_dummy_span(sym::err);
1229 1230 1231
            let (err_local, err_local_nid) = self.pat_ident(try_span, err_ident);
            let from_expr = {
                let from_path = &[sym::convert, sym::From, sym::from];
C
Camille GILLOT 已提交
1232 1233
                let err_expr = self.expr_ident_mut(try_span, err_ident, err_local_nid);
                self.expr_call_std_path(try_span, from_path, arena_vec![self; err_expr])
1234 1235
            };
            let from_err_expr =
1236
                self.wrap_in_try_constructor(sym::from_error, unstable_span, from_expr, try_span);
1237
            let thin_attrs = ThinVec::from(attrs);
1238
            let catch_scope = self.catch_scopes.last().copied();
1239 1240
            let ret_expr = if let Some(catch_node) = catch_scope {
                let target_id = Ok(self.lower_node_id(catch_node));
C
Camille GILLOT 已提交
1241
                self.arena.alloc(self.expr(
1242 1243
                    try_span,
                    hir::ExprKind::Break(
M
Mark Rousskov 已提交
1244
                        hir::Destination { label: None, target_id },
1245 1246 1247 1248 1249
                        Some(from_err_expr),
                    ),
                    thin_attrs,
                ))
            } else {
C
Camille GILLOT 已提交
1250 1251 1252 1253 1254
                self.arena.alloc(self.expr(
                    try_span,
                    hir::ExprKind::Ret(Some(from_err_expr)),
                    thin_attrs,
                ))
1255 1256 1257
            };

            let err_pat = self.pat_err(try_span, err_local);
1258
            self.arm(err_pat, ret_expr)
1259 1260
        };

C
Camille GILLOT 已提交
1261 1262 1263 1264 1265
        hir::ExprKind::Match(
            scrutinee,
            arena_vec![self; err_arm, ok_arm],
            hir::MatchSource::TryDesugar,
        )
1266
    }
1267

1268 1269 1270 1271
    // =========================================================================
    // Helper methods for building HIR.
    // =========================================================================

1272
    /// Constructs a `true` or `false` literal expression.
C
Camille GILLOT 已提交
1273
    pub(super) fn expr_bool(&mut self, span: Span, val: bool) -> &'hir hir::Expr<'hir> {
1274
        let lit = Spanned { span, node: LitKind::Bool(val) };
C
Camille GILLOT 已提交
1275
        self.arena.alloc(self.expr(span, hir::ExprKind::Lit(lit), ThinVec::new()))
1276 1277 1278 1279 1280 1281 1282 1283
    }

    /// Wrap the given `expr` in a terminating scope using `hir::ExprKind::DropTemps`.
    ///
    /// In terms of drop order, it has the same effect as wrapping `expr` in
    /// `{ let _t = $expr; _t }` but should provide better compile-time performance.
    ///
    /// The drop order can be important in e.g. `if expr { .. }`.
1284
    pub(super) fn expr_drop_temps(
1285 1286
        &mut self,
        span: Span,
C
Camille GILLOT 已提交
1287
        expr: &'hir hir::Expr<'hir>,
M
Mark Rousskov 已提交
1288
        attrs: AttrVec,
C
Camille GILLOT 已提交
1289 1290 1291 1292 1293 1294 1295 1296 1297
    ) -> &'hir hir::Expr<'hir> {
        self.arena.alloc(self.expr_drop_temps_mut(span, expr, attrs))
    }

    pub(super) fn expr_drop_temps_mut(
        &mut self,
        span: Span,
        expr: &'hir hir::Expr<'hir>,
        attrs: AttrVec,
C
Camille GILLOT 已提交
1298
    ) -> hir::Expr<'hir> {
1299 1300 1301 1302 1303 1304
        self.expr(span, hir::ExprKind::DropTemps(expr), attrs)
    }

    fn expr_match(
        &mut self,
        span: Span,
C
Camille GILLOT 已提交
1305 1306
        arg: &'hir hir::Expr<'hir>,
        arms: &'hir [hir::Arm<'hir>],
1307
        source: hir::MatchSource,
C
Camille GILLOT 已提交
1308
    ) -> hir::Expr<'hir> {
1309 1310 1311
        self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
    }

C
Camille GILLOT 已提交
1312
    fn expr_break(&mut self, span: Span, attrs: AttrVec) -> &'hir hir::Expr<'hir> {
1313
        let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
C
Camille GILLOT 已提交
1314
        self.arena.alloc(self.expr(span, expr_break, attrs))
1315 1316
    }

C
Camille GILLOT 已提交
1317
    fn expr_mut_addr_of(&mut self, span: Span, e: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
1318 1319
        self.expr(
            span,
1320
            hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Mut, e),
1321 1322
            ThinVec::new(),
        )
1323 1324
    }

C
Camille GILLOT 已提交
1325 1326
    fn expr_unit(&mut self, sp: Span) -> &'hir hir::Expr<'hir> {
        self.arena.alloc(self.expr(sp, hir::ExprKind::Tup(&[]), ThinVec::new()))
1327 1328 1329 1330 1331
    }

    fn expr_call(
        &mut self,
        span: Span,
C
Camille GILLOT 已提交
1332 1333
        e: &'hir hir::Expr<'hir>,
        args: &'hir [hir::Expr<'hir>],
C
Camille GILLOT 已提交
1334 1335
    ) -> &'hir hir::Expr<'hir> {
        self.arena.alloc(self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new()))
1336 1337 1338 1339 1340 1341 1342
    }

    // Note: associated functions must use `expr_call_std_path`.
    fn expr_call_std_path(
        &mut self,
        span: Span,
        path_components: &[Symbol],
C
Camille GILLOT 已提交
1343
        args: &'hir [hir::Expr<'hir>],
C
Camille GILLOT 已提交
1344
    ) -> &'hir hir::Expr<'hir> {
C
Camille GILLOT 已提交
1345 1346
        let path =
            self.arena.alloc(self.expr_std_path(span, path_components, None, ThinVec::new()));
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
        self.expr_call(span, path, args)
    }

    // Create an expression calling an associated function of an std type.
    //
    // Associated functions cannot be resolved through the normal `std_path` function,
    // as they are resolved differently and so cannot use `expr_call_std_path`.
    //
    // This function accepts the path component (`ty_path_components`) separately from
    // the name of the associated function (`assoc_fn_name`) in order to facilitate
    // separate resolution of the type and creation of a path referring to its associated
    // function.
    fn expr_call_std_assoc_fn(
        &mut self,
        ty_path_id: hir::HirId,
        span: Span,
        ty_path_components: &[Symbol],
        assoc_fn_name: &str,
C
Camille GILLOT 已提交
1365
        args: &'hir [hir::Expr<'hir>],
C
Camille GILLOT 已提交
1366
    ) -> hir::ExprKind<'hir> {
C
Camille GILLOT 已提交
1367
        let ty_path = self.std_path(span, ty_path_components, None, false);
C
Camille GILLOT 已提交
1368 1369 1370
        let ty =
            self.arena.alloc(self.ty_path(ty_path_id, span, hir::QPath::Resolved(None, ty_path)));
        let fn_seg = self.arena.alloc(hir::PathSegment::from_ident(Ident::from_str(assoc_fn_name)));
1371
        let fn_path = hir::QPath::TypeRelative(ty, fn_seg);
C
Camille GILLOT 已提交
1372 1373
        let fn_expr =
            self.arena.alloc(self.expr(span, hir::ExprKind::Path(fn_path), ThinVec::new()));
1374 1375 1376 1377 1378 1379 1380
        hir::ExprKind::Call(fn_expr, args)
    }

    fn expr_std_path(
        &mut self,
        span: Span,
        components: &[Symbol],
C
Camille GILLOT 已提交
1381
        params: Option<&'hir hir::GenericArgs<'hir>>,
M
Mazdak Farrokhzad 已提交
1382
        attrs: AttrVec,
C
Camille GILLOT 已提交
1383
    ) -> hir::Expr<'hir> {
1384
        let path = self.std_path(span, components, params, true);
C
Camille GILLOT 已提交
1385
        self.expr(span, hir::ExprKind::Path(hir::QPath::Resolved(None, path)), attrs)
1386 1387
    }

C
Camille GILLOT 已提交
1388 1389 1390 1391 1392
    pub(super) fn expr_ident(
        &mut self,
        sp: Span,
        ident: Ident,
        binding: hir::HirId,
C
Camille GILLOT 已提交
1393 1394 1395 1396 1397 1398 1399 1400 1401
    ) -> &'hir hir::Expr<'hir> {
        self.arena.alloc(self.expr_ident_mut(sp, ident, binding))
    }

    pub(super) fn expr_ident_mut(
        &mut self,
        sp: Span,
        ident: Ident,
        binding: hir::HirId,
C
Camille GILLOT 已提交
1402
    ) -> hir::Expr<'hir> {
1403 1404 1405 1406 1407 1408 1409 1410
        self.expr_ident_with_attrs(sp, ident, binding, ThinVec::new())
    }

    fn expr_ident_with_attrs(
        &mut self,
        span: Span,
        ident: Ident,
        binding: hir::HirId,
M
Mazdak Farrokhzad 已提交
1411
        attrs: AttrVec,
C
Camille GILLOT 已提交
1412
    ) -> hir::Expr<'hir> {
1413 1414
        let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
            None,
C
Camille GILLOT 已提交
1415
            self.arena.alloc(hir::Path {
1416 1417
                span,
                res: Res::Local(binding),
C
Camille GILLOT 已提交
1418
                segments: arena_vec![self; hir::PathSegment::from_ident(ident)],
1419 1420 1421 1422 1423 1424
            }),
        ));

        self.expr(span, expr_path, attrs)
    }

C
Camille GILLOT 已提交
1425
    fn expr_unsafe(&mut self, expr: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
1426 1427 1428 1429
        let hir_id = self.next_id();
        let span = expr.span;
        self.expr(
            span,
M
Mark Rousskov 已提交
1430
            hir::ExprKind::Block(
C
Camille GILLOT 已提交
1431 1432
                self.arena.alloc(hir::Block {
                    stmts: &[],
M
Mark Rousskov 已提交
1433 1434
                    expr: Some(expr),
                    hir_id,
1435
                    rules: hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::CompilerGenerated),
M
Mark Rousskov 已提交
1436 1437 1438 1439 1440
                    span,
                    targeted_by_break: false,
                }),
                None,
            ),
1441 1442 1443 1444
            ThinVec::new(),
        )
    }

C
Camille GILLOT 已提交
1445
    fn expr_block_empty(&mut self, span: Span) -> &'hir hir::Expr<'hir> {
C
Camille GILLOT 已提交
1446
        let blk = self.block_all(span, &[], None);
C
Camille GILLOT 已提交
1447 1448
        let expr = self.expr_block(blk, ThinVec::new());
        self.arena.alloc(expr)
1449 1450
    }

C
Camille GILLOT 已提交
1451 1452 1453 1454 1455
    pub(super) fn expr_block(
        &mut self,
        b: &'hir hir::Block<'hir>,
        attrs: AttrVec,
    ) -> hir::Expr<'hir> {
1456 1457 1458
        self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
    }

C
Camille GILLOT 已提交
1459 1460 1461 1462 1463 1464
    pub(super) fn expr(
        &mut self,
        span: Span,
        kind: hir::ExprKind<'hir>,
        attrs: AttrVec,
    ) -> hir::Expr<'hir> {
V
varkor 已提交
1465
        hir::Expr { hir_id: self.next_id(), kind, span, attrs }
1466
    }
1467

C
Camille GILLOT 已提交
1468
    fn field(&mut self, ident: Ident, expr: &'hir hir::Expr<'hir>, span: Span) -> hir::Field<'hir> {
M
Mark Rousskov 已提交
1469
        hir::Field { hir_id: self.next_id(), ident, span, expr, is_shorthand: false }
1470
    }
1471

C
Camille GILLOT 已提交
1472
    fn arm(&mut self, pat: &'hir hir::Pat<'hir>, expr: &'hir hir::Expr<'hir>) -> hir::Arm<'hir> {
1473 1474
        hir::Arm {
            hir_id: self.next_id(),
C
Camille GILLOT 已提交
1475
            attrs: &[],
1476
            pat,
1477 1478 1479 1480 1481
            guard: None,
            span: expr.span,
            body: expr,
        }
    }
1482
}