1 use super::{ImplTraitContext, LoweringContext, ParamMode, ParenthesizedGenericArgs};
4 use rustc_ast::ptr::P as AstP;
6 use rustc_data_structures::stack::ensure_sufficient_stack;
7 use rustc_data_structures::thin_vec::ThinVec;
8 use rustc_errors::struct_span_err;
10 use rustc_hir::def::Res;
11 use rustc_hir::definitions::DefPathData;
12 use rustc_session::parse::feature_err;
13 use rustc_span::hygiene::ExpnId;
14 use rustc_span::source_map::{respan, DesugaringKind, Span, Spanned};
15 use rustc_span::symbol::{sym, Ident, Symbol};
16 use rustc_span::{hygiene::ForLoopLoc, DUMMY_SP};
18 impl<'hir> LoweringContext<'_, 'hir> {
19 fn lower_exprs(&mut self, exprs: &[AstP<Expr>]) -> &'hir [hir::Expr<'hir>] {
20 self.arena.alloc_from_iter(exprs.iter().map(|x| self.lower_expr_mut(x)))
23 pub(super) fn lower_expr(&mut self, e: &Expr) -> &'hir hir::Expr<'hir> {
24 self.arena.alloc(self.lower_expr_mut(e))
27 pub(super) fn lower_expr_mut(&mut self, e: &Expr) -> hir::Expr<'hir> {
28 ensure_sufficient_stack(|| {
29 let kind = match e.kind {
30 ExprKind::Box(ref inner) => hir::ExprKind::Box(self.lower_expr(inner)),
31 ExprKind::Array(ref exprs) => hir::ExprKind::Array(self.lower_exprs(exprs)),
32 ExprKind::ConstBlock(ref anon_const) => {
33 let anon_const = self.lower_anon_const(anon_const);
34 hir::ExprKind::ConstBlock(anon_const)
36 ExprKind::Repeat(ref expr, ref count) => {
37 let expr = self.lower_expr(expr);
38 let count = self.lower_anon_const(count);
39 hir::ExprKind::Repeat(expr, count)
41 ExprKind::Tup(ref elts) => hir::ExprKind::Tup(self.lower_exprs(elts)),
42 ExprKind::Call(ref f, ref args) => {
43 if let Some(legacy_args) = self.resolver.legacy_const_generic_args(f) {
44 self.lower_legacy_const_generics((**f).clone(), args.clone(), &legacy_args)
46 let f = self.lower_expr(f);
47 hir::ExprKind::Call(f, self.lower_exprs(args))
50 ExprKind::MethodCall(ref seg, ref args, span) => {
51 let hir_seg = self.arena.alloc(self.lower_path_segment(
56 ParenthesizedGenericArgs::Err,
57 ImplTraitContext::disallowed(),
60 let args = self.lower_exprs(args);
61 hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args, span)
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)
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)
74 ExprKind::Lit(ref l) => hir::ExprKind::Lit(respan(l.span, l.kind.clone())),
75 ExprKind::Cast(ref expr, ref ty) => {
76 let expr = self.lower_expr(expr);
77 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
78 hir::ExprKind::Cast(expr, ty)
80 ExprKind::Type(ref expr, ref ty) => {
81 let expr = self.lower_expr(expr);
82 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
83 hir::ExprKind::Type(expr, ty)
85 ExprKind::AddrOf(k, m, ref ohs) => {
86 let ohs = self.lower_expr(ohs);
87 hir::ExprKind::AddrOf(k, m, ohs)
89 ExprKind::Let(ref pat, ref scrutinee) => {
90 self.lower_expr_let(e.span, pat, scrutinee)
92 ExprKind::If(ref cond, ref then, ref else_opt) => match cond.kind {
93 ExprKind::Let(ref pat, ref scrutinee) => {
94 self.lower_expr_if_let(e.span, pat, scrutinee, then, else_opt.as_deref())
96 ExprKind::Paren(ref paren) => match paren.peel_parens().kind {
97 ExprKind::Let(ref pat, ref scrutinee) => {
98 // A user has written `if (let Some(x) = foo) {`, we want to avoid
99 // confusing them with mentions of nightly features.
100 // If this logic is changed, you will also likely need to touch
101 // `unused::UnusedParens::check_expr`.
102 self.if_let_expr_with_parens(cond, &paren.peel_parens());
103 self.lower_expr_if_let(
111 _ => self.lower_expr_if(cond, then, else_opt.as_deref()),
113 _ => self.lower_expr_if(cond, then, else_opt.as_deref()),
115 ExprKind::While(ref cond, ref body, opt_label) => self
116 .with_loop_scope(e.id, |this| {
117 this.lower_expr_while_in_loop_scope(e.span, cond, body, opt_label)
119 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
121 this.lower_block(body, false),
123 hir::LoopSource::Loop,
127 ExprKind::TryBlock(ref body) => self.lower_expr_try_block(body),
128 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
129 self.lower_expr(expr),
130 self.arena.alloc_from_iter(arms.iter().map(|x| self.lower_arm(x))),
131 hir::MatchSource::Normal,
133 ExprKind::Async(capture_clause, closure_node_id, ref block) => self
139 hir::AsyncGeneratorKind::Block,
140 |this| this.with_new_scopes(|this| this.lower_block_expr(block)),
142 ExprKind::Await(ref expr) => self.lower_expr_await(e.span, expr),
151 if let Async::Yes { closure_id, .. } = asyncness {
152 self.lower_expr_async_closure(
160 self.lower_expr_closure(
169 ExprKind::Block(ref blk, opt_label) => {
170 hir::ExprKind::Block(self.lower_block(blk, opt_label.is_some()), opt_label)
172 ExprKind::Assign(ref el, ref er, span) => {
173 self.lower_expr_assign(el, er, span, e.span)
175 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
176 self.lower_binop(op),
180 ExprKind::Field(ref el, ident) => hir::ExprKind::Field(self.lower_expr(el), ident),
181 ExprKind::Index(ref el, ref er) => {
182 hir::ExprKind::Index(self.lower_expr(el), self.lower_expr(er))
184 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
185 self.lower_expr_range_closed(e.span, e1, e2)
187 ExprKind::Range(ref e1, ref e2, lims) => {
188 self.lower_expr_range(e.span, e1.as_deref(), e2.as_deref(), lims)
190 ExprKind::Underscore => {
194 "in expressions, `_` can only be used on the left-hand side of an assignment",
196 .span_label(e.span, "`_` not allowed here")
200 ExprKind::Path(ref qself, ref path) => {
201 let qpath = self.lower_qpath(
206 ImplTraitContext::disallowed(),
208 hir::ExprKind::Path(qpath)
210 ExprKind::Break(opt_label, ref opt_expr) => {
211 let opt_expr = opt_expr.as_ref().map(|x| self.lower_expr(x));
212 hir::ExprKind::Break(self.lower_jump_destination(e.id, opt_label), opt_expr)
214 ExprKind::Continue(opt_label) => {
215 hir::ExprKind::Continue(self.lower_jump_destination(e.id, opt_label))
217 ExprKind::Ret(ref e) => {
218 let e = e.as_ref().map(|x| self.lower_expr(x));
219 hir::ExprKind::Ret(e)
221 ExprKind::InlineAsm(ref asm) => {
222 hir::ExprKind::InlineAsm(self.lower_inline_asm(e.span, asm))
224 ExprKind::LlvmInlineAsm(ref asm) => self.lower_expr_llvm_asm(asm),
225 ExprKind::Struct(ref se) => {
226 let rest = match &se.rest {
227 StructRest::Base(e) => Some(self.lower_expr(e)),
228 StructRest::Rest(sp) => {
230 .struct_span_err(*sp, "base expression required after `..`")
231 .span_label(*sp, "add a base expression here")
233 Some(&*self.arena.alloc(self.expr_err(*sp)))
235 StructRest::None => None,
237 hir::ExprKind::Struct(
238 self.arena.alloc(self.lower_qpath(
243 ImplTraitContext::disallowed(),
246 .alloc_from_iter(se.fields.iter().map(|x| self.lower_expr_field(x))),
250 ExprKind::Yield(ref opt_expr) => self.lower_expr_yield(e.span, opt_expr.as_deref()),
251 ExprKind::Err => hir::ExprKind::Err,
252 ExprKind::Try(ref sub_expr) => self.lower_expr_try(e.span, sub_expr),
253 ExprKind::Paren(ref ex) => {
254 let mut ex = self.lower_expr_mut(ex);
255 // Include parens in span, but only if it is a super-span.
256 if e.span.contains(ex.span) {
259 // Merge attributes into the inner expression.
260 if !e.attrs.is_empty() {
261 let old_attrs = self.attrs.get(&ex.hir_id).map(|la| *la).unwrap_or(&[]);
264 &*self.arena.alloc_from_iter(
267 .map(|a| self.lower_attr(a))
268 .chain(old_attrs.iter().cloned()),
275 // Desugar `ExprForLoop`
276 // from: `[opt_ident]: for <pat> in <head> <body>`
277 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
278 return self.lower_expr_for(e, pat, head, body, opt_label);
280 ExprKind::MacCall(_) => panic!("{:?} shouldn't exist here", e.span),
283 let hir_id = self.lower_node_id(e.id);
284 self.lower_attrs(hir_id, &e.attrs);
285 hir::Expr { hir_id, kind, span: e.span }
289 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
291 UnOp::Deref => hir::UnOp::Deref,
292 UnOp::Not => hir::UnOp::Not,
293 UnOp::Neg => hir::UnOp::Neg,
297 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
300 BinOpKind::Add => hir::BinOpKind::Add,
301 BinOpKind::Sub => hir::BinOpKind::Sub,
302 BinOpKind::Mul => hir::BinOpKind::Mul,
303 BinOpKind::Div => hir::BinOpKind::Div,
304 BinOpKind::Rem => hir::BinOpKind::Rem,
305 BinOpKind::And => hir::BinOpKind::And,
306 BinOpKind::Or => hir::BinOpKind::Or,
307 BinOpKind::BitXor => hir::BinOpKind::BitXor,
308 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
309 BinOpKind::BitOr => hir::BinOpKind::BitOr,
310 BinOpKind::Shl => hir::BinOpKind::Shl,
311 BinOpKind::Shr => hir::BinOpKind::Shr,
312 BinOpKind::Eq => hir::BinOpKind::Eq,
313 BinOpKind::Lt => hir::BinOpKind::Lt,
314 BinOpKind::Le => hir::BinOpKind::Le,
315 BinOpKind::Ne => hir::BinOpKind::Ne,
316 BinOpKind::Ge => hir::BinOpKind::Ge,
317 BinOpKind::Gt => hir::BinOpKind::Gt,
323 fn lower_legacy_const_generics(
326 args: Vec<AstP<Expr>>,
327 legacy_args_idx: &[usize],
328 ) -> hir::ExprKind<'hir> {
329 let path = match f.kind {
330 ExprKind::Path(None, ref mut path) => path,
334 // Split the arguments into const generics and normal arguments
335 let mut real_args = vec![];
336 let mut generic_args = vec![];
337 for (idx, arg) in args.into_iter().enumerate() {
338 if legacy_args_idx.contains(&idx) {
339 let parent_def_id = self.current_hir_id_owner.0;
340 let node_id = self.resolver.next_node_id();
342 // Add a definition for the in-band const def.
343 self.resolver.create_def(
346 DefPathData::AnonConst,
351 let anon_const = AnonConst { id: node_id, value: arg };
352 generic_args.push(AngleBracketedArg::Arg(GenericArg::Const(anon_const)));
358 // Add generic args to the last element of the path.
359 let last_segment = path.segments.last_mut().unwrap();
360 assert!(last_segment.args.is_none());
361 last_segment.args = Some(AstP(GenericArgs::AngleBracketed(AngleBracketedArgs {
366 // Now lower everything as normal.
367 let f = self.lower_expr(&f);
368 hir::ExprKind::Call(f, self.lower_exprs(&real_args))
371 fn if_let_expr_with_parens(&mut self, cond: &Expr, paren: &Expr) {
372 let start = cond.span.until(paren.span);
373 let end = paren.span.shrink_to_hi().until(cond.span.shrink_to_hi());
377 "invalid parentheses around `let` expression in `if let`",
379 .multipart_suggestion(
380 "`if let` needs to be written without parentheses",
381 vec![(start, String::new()), (end, String::new())],
382 rustc_errors::Applicability::MachineApplicable,
385 // Ideally, we'd remove the feature gating of a `let` expression since we are already
386 // complaining about it here, but `feature_gate::check_crate` has already run by now:
387 // self.sess.parse_sess.gated_spans.ungate_last(sym::let_chains, paren.span);
390 /// Emit an error and lower `ast::ExprKind::Let(pat, scrutinee)` into:
392 /// match scrutinee { pats => true, _ => false }
394 fn lower_expr_let(&mut self, span: Span, pat: &Pat, scrutinee: &Expr) -> hir::ExprKind<'hir> {
395 // If we got here, the `let` expression is not allowed.
397 if self.sess.opts.unstable_features.is_nightly_build() {
399 .struct_span_err(span, "`let` expressions are not supported here")
401 "only supported directly without parentheses in conditions of `if`- and \
402 `while`-expressions, as well as in `let` chains within parentheses",
407 .struct_span_err(span, "expected expression, found statement (`let`)")
408 .note("variable declaration using `let` is a statement")
412 // For better recovery, we emit:
414 // match scrutinee { pat => true, _ => false }
416 // While this doesn't fully match the user's intent, it has key advantages:
417 // 1. We can avoid using `abort_if_errors`.
418 // 2. We can typeck both `pat` and `scrutinee`.
419 // 3. `pat` is allowed to be refutable.
420 // 4. The return type of the block is `bool` which seems like what the user wanted.
421 let scrutinee = self.lower_expr(scrutinee);
423 let pat = self.lower_pat(pat);
424 let expr = self.expr_bool(span, true);
428 let pat = self.pat_wild(span);
429 let expr = self.expr_bool(span, false);
432 hir::ExprKind::Match(
434 arena_vec![self; then_arm, else_arm],
435 hir::MatchSource::Normal,
443 else_opt: Option<&Expr>,
444 ) -> hir::ExprKind<'hir> {
445 macro_rules! make_if {
447 let cond = self.lower_expr(cond);
448 let then_expr = self.lower_block_expr(then);
449 hir::ExprKind::If(cond, self.arena.alloc(then_expr), $opt)
452 if let Some(rslt) = else_opt {
453 make_if!(Some(self.lower_expr(rslt)))
459 fn lower_expr_if_let(
465 else_opt: Option<&Expr>,
466 ) -> hir::ExprKind<'hir> {
467 // FIXME(#53667): handle lowering of && and parens.
469 // `_ => else_block` where `else_block` is `{}` if there's `None`:
470 let else_pat = self.pat_wild(span);
471 let (else_expr, contains_else_clause) = match else_opt {
472 None => (self.expr_block_empty(span.shrink_to_hi()), false),
473 Some(els) => (self.lower_expr(els), true),
475 let else_arm = self.arm(else_pat, else_expr);
477 // Handle then + scrutinee:
478 let scrutinee = self.lower_expr(scrutinee);
479 let then_pat = self.lower_pat(pat);
481 let then_expr = self.lower_block_expr(then);
482 let then_arm = self.arm(then_pat, self.arena.alloc(then_expr));
484 let desugar = hir::MatchSource::IfLetDesugar { contains_else_clause };
485 hir::ExprKind::Match(scrutinee, arena_vec![self; then_arm, else_arm], desugar)
488 fn lower_expr_while_in_loop_scope(
493 opt_label: Option<Label>,
494 ) -> hir::ExprKind<'hir> {
495 // FIXME(#53667): handle lowering of && and parens.
497 // Note that the block AND the condition are evaluated in the loop scope.
498 // This is done to allow `break` from inside the condition of the loop.
502 let else_pat = self.pat_wild(span);
503 let else_expr = self.expr_break(span, ThinVec::new());
504 self.arm(else_pat, else_expr)
507 // Handle then + scrutinee:
508 let (then_pat, scrutinee, desugar, source) = match cond.kind {
509 ExprKind::Let(ref pat, ref scrutinee) => {
512 // [opt_ident]: loop {
513 // match <sub_expr> {
518 let scrutinee = self.with_loop_condition_scope(|t| t.lower_expr(scrutinee));
519 let pat = self.lower_pat(pat);
520 (pat, scrutinee, hir::MatchSource::WhileLetDesugar, hir::LoopSource::WhileLet)
523 // We desugar: `'label: while $cond $body` into:
527 // match drop-temps { $cond } {
535 let cond = self.with_loop_condition_scope(|this| this.lower_expr(cond));
537 self.mark_span_with_reason(DesugaringKind::CondTemporary, cond.span, None);
538 // Wrap in a construct equivalent to `{ let _t = $cond; _t }`
539 // to preserve drop semantics since `while cond { ... }` does not
540 // let temporaries live outside of `cond`.
541 let cond = self.expr_drop_temps(span_block, cond, ThinVec::new());
543 let pat = self.pat_bool(span, true);
544 (pat, cond, hir::MatchSource::WhileDesugar, hir::LoopSource::While)
547 let then_expr = self.lower_block_expr(body);
548 let then_arm = self.arm(then_pat, self.arena.alloc(then_expr));
550 // `match <scrutinee> { ... }`
552 self.expr_match(span, scrutinee, arena_vec![self; then_arm, else_arm], desugar);
554 // `[opt_ident]: loop { ... }`
556 self.block_expr(self.arena.alloc(match_expr)),
559 span.with_hi(cond.span.hi()),
563 /// Desugar `try { <stmts>; <expr> }` into `{ <stmts>; ::std::ops::Try::from_output(<expr>) }`,
564 /// `try { <stmts>; }` into `{ <stmts>; ::std::ops::Try::from_output(()) }`
565 /// and save the block id to use it as a break target for desugaring of the `?` operator.
566 fn lower_expr_try_block(&mut self, body: &Block) -> hir::ExprKind<'hir> {
567 self.with_catch_scope(body.id, |this| {
568 let mut block = this.lower_block_noalloc(body, true);
570 // Final expression of the block (if present) or `()` with span at the end of block
571 let (try_span, tail_expr) = if let Some(expr) = block.expr.take() {
573 this.mark_span_with_reason(
574 DesugaringKind::TryBlock,
576 this.allow_try_trait.clone(),
581 let try_span = this.mark_span_with_reason(
582 DesugaringKind::TryBlock,
583 this.sess.source_map().end_point(body.span),
584 this.allow_try_trait.clone(),
587 (try_span, this.expr_unit(try_span))
590 let ok_wrapped_span =
591 this.mark_span_with_reason(DesugaringKind::TryBlock, tail_expr.span, None);
593 // `::std::ops::Try::from_output($tail_expr)`
594 block.expr = Some(this.wrap_in_try_constructor(
595 hir::LangItem::TryTraitFromOutput,
601 hir::ExprKind::Block(this.arena.alloc(block), None)
605 fn wrap_in_try_constructor(
607 lang_item: hir::LangItem,
609 expr: &'hir hir::Expr<'hir>,
611 ) -> &'hir hir::Expr<'hir> {
613 self.arena.alloc(self.expr_lang_item_path(method_span, lang_item, ThinVec::new()));
614 self.expr_call(overall_span, constructor, std::slice::from_ref(expr))
617 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm<'hir> {
618 let pat = self.lower_pat(&arm.pat);
619 let guard = arm.guard.as_ref().map(|cond| {
620 if let ExprKind::Let(ref pat, ref scrutinee) = cond.kind {
621 hir::Guard::IfLet(self.lower_pat(pat), self.lower_expr(scrutinee))
623 hir::Guard::If(self.lower_expr(cond))
626 let hir_id = self.next_id();
627 self.lower_attrs(hir_id, &arm.attrs);
628 hir::Arm { hir_id, pat, guard, body: self.lower_expr(&arm.body), span: arm.span }
631 /// Lower an `async` construct to a generator that is then wrapped so it implements `Future`.
636 /// std::future::from_generator(static move? |_task_context| -> <ret_ty> {
640 pub(super) fn make_async_expr(
642 capture_clause: CaptureBy,
643 closure_node_id: NodeId,
644 ret_ty: Option<AstP<Ty>>,
646 async_gen_kind: hir::AsyncGeneratorKind,
647 body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
648 ) -> hir::ExprKind<'hir> {
649 let output = match ret_ty {
650 Some(ty) => hir::FnRetTy::Return(self.lower_ty(&ty, ImplTraitContext::disallowed())),
651 None => hir::FnRetTy::DefaultReturn(span),
654 // Resume argument type. We let the compiler infer this to simplify the lowering. It is
655 // fully constrained by `future::from_generator`.
656 let input_ty = hir::Ty { hir_id: self.next_id(), kind: hir::TyKind::Infer, span };
658 // The closure/generator `FnDecl` takes a single (resume) argument of type `input_ty`.
659 let decl = self.arena.alloc(hir::FnDecl {
660 inputs: arena_vec![self; input_ty],
663 implicit_self: hir::ImplicitSelfKind::None,
666 // Lower the argument pattern/ident. The ident is used again in the `.await` lowering.
667 let (pat, task_context_hid) = self.pat_ident_binding_mode(
669 Ident::with_dummy_span(sym::_task_context),
670 hir::BindingAnnotation::Mutable,
672 let param = hir::Param { hir_id: self.next_id(), pat, ty_span: span, span };
673 let params = arena_vec![self; param];
675 let body_id = self.lower_body(move |this| {
676 this.generator_kind = Some(hir::GeneratorKind::Async(async_gen_kind));
678 let old_ctx = this.task_context;
679 this.task_context = Some(task_context_hid);
680 let res = body(this);
681 this.task_context = old_ctx;
685 // `static |_task_context| -> <ret_ty> { body }`:
686 let generator_kind = hir::ExprKind::Closure(
691 Some(hir::Movability::Static),
694 hir::Expr { hir_id: self.lower_node_id(closure_node_id), kind: generator_kind, span };
696 // `future::from_generator`:
698 self.mark_span_with_reason(DesugaringKind::Async, span, self.allow_gen_future.clone());
700 self.expr_lang_item_path(unstable_span, hir::LangItem::FromGenerator, ThinVec::new());
702 // `future::from_generator(generator)`:
703 hir::ExprKind::Call(self.arena.alloc(gen_future), arena_vec![self; generator])
706 /// Desugar `<expr>.await` into:
709 /// mut pinned => loop {
710 /// match unsafe { ::std::future::Future::poll(
711 /// <::std::pin::Pin>::new_unchecked(&mut pinned),
712 /// ::std::future::get_context(task_context),
714 /// ::std::task::Poll::Ready(result) => break result,
715 /// ::std::task::Poll::Pending => {}
717 /// task_context = yield ();
721 fn lower_expr_await(&mut self, await_span: Span, expr: &Expr) -> hir::ExprKind<'hir> {
722 match self.generator_kind {
723 Some(hir::GeneratorKind::Async(_)) => {}
724 Some(hir::GeneratorKind::Gen) | None => {
725 let mut err = struct_span_err!(
729 "`await` is only allowed inside `async` functions and blocks"
731 err.span_label(await_span, "only allowed inside `async` functions and blocks");
732 if let Some(item_sp) = self.current_item {
733 err.span_label(item_sp, "this is not `async`");
738 let span = self.mark_span_with_reason(DesugaringKind::Await, await_span, None);
739 let gen_future_span = self.mark_span_with_reason(
740 DesugaringKind::Await,
742 self.allow_gen_future.clone(),
744 let expr = self.lower_expr(expr);
746 let pinned_ident = Ident::with_dummy_span(sym::pinned);
747 let (pinned_pat, pinned_pat_hid) =
748 self.pat_ident_binding_mode(span, pinned_ident, hir::BindingAnnotation::Mutable);
750 let task_context_ident = Ident::with_dummy_span(sym::_task_context);
753 // ::std::future::Future::poll(
754 // ::std::pin::Pin::new_unchecked(&mut pinned),
755 // ::std::future::get_context(task_context),
759 let pinned = self.expr_ident(span, pinned_ident, pinned_pat_hid);
760 let ref_mut_pinned = self.expr_mut_addr_of(span, pinned);
761 let task_context = if let Some(task_context_hid) = self.task_context {
762 self.expr_ident_mut(span, task_context_ident, task_context_hid)
764 // Use of `await` outside of an async context, we cannot use `task_context` here.
767 let new_unchecked = self.expr_call_lang_item_fn_mut(
769 hir::LangItem::PinNewUnchecked,
770 arena_vec![self; ref_mut_pinned],
772 let get_context = self.expr_call_lang_item_fn_mut(
774 hir::LangItem::GetContext,
775 arena_vec![self; task_context],
777 let call = self.expr_call_lang_item_fn(
779 hir::LangItem::FuturePoll,
780 arena_vec![self; new_unchecked, get_context],
782 self.arena.alloc(self.expr_unsafe(call))
785 // `::std::task::Poll::Ready(result) => break result`
786 let loop_node_id = self.resolver.next_node_id();
787 let loop_hir_id = self.lower_node_id(loop_node_id);
789 let x_ident = Ident::with_dummy_span(sym::result);
790 let (x_pat, x_pat_hid) = self.pat_ident(span, x_ident);
791 let x_expr = self.expr_ident(span, x_ident, x_pat_hid);
792 let ready_field = self.single_pat_field(span, x_pat);
793 let ready_pat = self.pat_lang_item_variant(span, hir::LangItem::PollReady, ready_field);
794 let break_x = self.with_loop_scope(loop_node_id, move |this| {
796 hir::ExprKind::Break(this.lower_loop_destination(None), Some(x_expr));
797 this.arena.alloc(this.expr(await_span, expr_break, ThinVec::new()))
799 self.arm(ready_pat, break_x)
802 // `::std::task::Poll::Pending => {}`
804 let pending_pat = self.pat_lang_item_variant(span, hir::LangItem::PollPending, &[]);
805 let empty_block = self.expr_block_empty(span);
806 self.arm(pending_pat, empty_block)
809 let inner_match_stmt = {
810 let match_expr = self.expr_match(
813 arena_vec![self; ready_arm, pending_arm],
814 hir::MatchSource::AwaitDesugar,
816 self.stmt_expr(span, match_expr)
819 // task_context = yield ();
821 let unit = self.expr_unit(span);
822 let yield_expr = self.expr(
824 hir::ExprKind::Yield(unit, hir::YieldSource::Await { expr: Some(expr.hir_id) }),
827 let yield_expr = self.arena.alloc(yield_expr);
829 if let Some(task_context_hid) = self.task_context {
830 let lhs = self.expr_ident(span, task_context_ident, task_context_hid);
832 self.expr(span, hir::ExprKind::Assign(lhs, yield_expr, span), AttrVec::new());
833 self.stmt_expr(span, assign)
835 // Use of `await` outside of an async context. Return `yield_expr` so that we can
836 // proceed with type checking.
837 self.stmt(span, hir::StmtKind::Semi(yield_expr))
841 let loop_block = self.block_all(span, arena_vec![self; inner_match_stmt, yield_stmt], None);
844 let loop_expr = self.arena.alloc(hir::Expr {
846 kind: hir::ExprKind::Loop(loop_block, None, hir::LoopSource::Loop, span),
850 // mut pinned => loop { ... }
851 let pinned_arm = self.arm(pinned_pat, loop_expr);
854 // mut pinned => loop { .. }
856 hir::ExprKind::Match(expr, arena_vec![self; pinned_arm], hir::MatchSource::AwaitDesugar)
859 fn lower_expr_closure(
861 capture_clause: CaptureBy,
862 movability: Movability,
866 ) -> hir::ExprKind<'hir> {
867 let (body_id, generator_option) = self.with_new_scopes(move |this| {
868 let prev = this.current_item;
869 this.current_item = Some(fn_decl_span);
870 let mut generator_kind = None;
871 let body_id = this.lower_fn_body(decl, |this| {
872 let e = this.lower_expr_mut(body);
873 generator_kind = this.generator_kind;
876 let generator_option =
877 this.generator_movability_for_fn(&decl, fn_decl_span, generator_kind, movability);
878 this.current_item = prev;
879 (body_id, generator_option)
882 // Lower outside new scope to preserve `is_in_loop_condition`.
883 let fn_decl = self.lower_fn_decl(decl, None, false, None);
885 hir::ExprKind::Closure(capture_clause, fn_decl, body_id, fn_decl_span, generator_option)
888 fn generator_movability_for_fn(
892 generator_kind: Option<hir::GeneratorKind>,
893 movability: Movability,
894 ) -> Option<hir::Movability> {
895 match generator_kind {
896 Some(hir::GeneratorKind::Gen) => {
897 if decl.inputs.len() > 1 {
902 "too many parameters for a generator (expected 0 or 1 parameters)"
908 Some(hir::GeneratorKind::Async(_)) => {
909 panic!("non-`async` closure body turned `async` during lowering");
912 if movability == Movability::Static {
913 struct_span_err!(self.sess, fn_decl_span, E0697, "closures cannot be static")
921 fn lower_expr_async_closure(
923 capture_clause: CaptureBy,
928 ) -> hir::ExprKind<'hir> {
930 FnDecl { inputs: decl.inputs.clone(), output: FnRetTy::Default(fn_decl_span) };
932 let body_id = self.with_new_scopes(|this| {
933 // FIXME(cramertj): allow `async` non-`move` closures with arguments.
934 if capture_clause == CaptureBy::Ref && !decl.inputs.is_empty() {
939 "`async` non-`move` closures with parameters are not currently supported",
942 "consider using `let` statements to manually capture \
943 variables by reference before entering an `async move` closure",
948 // Transform `async |x: u8| -> X { ... }` into
949 // `|x: u8| future_from_generator(|| -> X { ... })`.
950 let body_id = this.lower_fn_body(&outer_decl, |this| {
952 if let FnRetTy::Ty(ty) = &decl.output { Some(ty.clone()) } else { None };
953 let async_body = this.make_async_expr(
958 hir::AsyncGeneratorKind::Closure,
959 |this| this.with_new_scopes(|this| this.lower_expr_mut(body)),
961 this.expr(fn_decl_span, async_body, ThinVec::new())
966 // We need to lower the declaration outside the new scope, because we
967 // have to conserve the state of being inside a loop condition for the
968 // closure argument types.
969 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
971 hir::ExprKind::Closure(capture_clause, fn_decl, body_id, fn_decl_span, None)
974 /// Destructure the LHS of complex assignments.
975 /// For instance, lower `(a, b) = t` to `{ let (lhs1, lhs2) = t; a = lhs1; b = lhs2; }`.
976 fn lower_expr_assign(
982 ) -> hir::ExprKind<'hir> {
983 // Return early in case of an ordinary assignment.
984 fn is_ordinary(lower_ctx: &mut LoweringContext<'_, '_>, lhs: &Expr) -> bool {
987 | ExprKind::Struct(..)
989 | ExprKind::Underscore => false,
990 // Check for tuple struct constructor.
991 ExprKind::Call(callee, ..) => lower_ctx.extract_tuple_struct_path(callee).is_none(),
992 ExprKind::Paren(e) => {
994 // We special-case `(..)` for consistency with patterns.
995 ExprKind::Range(None, None, RangeLimits::HalfOpen) => false,
996 _ => is_ordinary(lower_ctx, e),
1002 if is_ordinary(self, lhs) {
1003 return hir::ExprKind::Assign(self.lower_expr(lhs), self.lower_expr(rhs), eq_sign_span);
1005 if !self.sess.features_untracked().destructuring_assignment {
1007 &self.sess.parse_sess,
1008 sym::destructuring_assignment,
1010 "destructuring assignments are unstable",
1012 .span_label(lhs.span, "cannot assign to this expression")
1016 let mut assignments = vec![];
1018 // The LHS becomes a pattern: `(lhs1, lhs2)`.
1019 let pat = self.destructure_assign(lhs, eq_sign_span, &mut assignments);
1020 let rhs = self.lower_expr(rhs);
1022 // Introduce a `let` for destructuring: `let (lhs1, lhs2) = t`.
1023 let destructure_let = self.stmt_let_pat(
1028 hir::LocalSource::AssignDesugar(eq_sign_span),
1031 // `a = lhs1; b = lhs2;`.
1034 .alloc_from_iter(std::iter::once(destructure_let).chain(assignments.into_iter()));
1036 // Wrap everything in a block.
1037 hir::ExprKind::Block(&self.block_all(whole_span, stmts, None), None)
1040 /// If the given expression is a path to a tuple struct, returns that path.
1041 /// It is not a complete check, but just tries to reject most paths early
1042 /// if they are not tuple structs.
1043 /// Type checking will take care of the full validation later.
1044 fn extract_tuple_struct_path<'a>(
1047 ) -> Option<(&'a Option<QSelf>, &'a Path)> {
1048 if let ExprKind::Path(qself, path) = &expr.kind {
1049 // Does the path resolve to something disallowed in a tuple struct/variant pattern?
1050 if let Some(partial_res) = self.resolver.get_partial_res(expr.id) {
1051 if partial_res.unresolved_segments() == 0
1052 && !partial_res.base_res().expected_in_tuple_struct_pat()
1057 return Some((qself, path));
1062 /// Convert the LHS of a destructuring assignment to a pattern.
1063 /// Each sub-assignment is recorded in `assignments`.
1064 fn destructure_assign(
1068 assignments: &mut Vec<hir::Stmt<'hir>>,
1069 ) -> &'hir hir::Pat<'hir> {
1071 // Underscore pattern.
1072 ExprKind::Underscore => {
1073 return self.pat_without_dbm(lhs.span, hir::PatKind::Wild);
1076 ExprKind::Array(elements) => {
1078 self.destructure_sequence(elements, "slice", eq_sign_span, assignments);
1079 let slice_pat = if let Some((i, span)) = rest {
1080 let (before, after) = pats.split_at(i);
1081 hir::PatKind::Slice(
1083 Some(self.pat_without_dbm(span, hir::PatKind::Wild)),
1087 hir::PatKind::Slice(pats, None, &[])
1089 return self.pat_without_dbm(lhs.span, slice_pat);
1092 ExprKind::Call(callee, args) => {
1093 if let Some((qself, path)) = self.extract_tuple_struct_path(callee) {
1094 let (pats, rest) = self.destructure_sequence(
1096 "tuple struct or variant",
1100 let qpath = self.lower_qpath(
1104 ParamMode::Optional,
1105 ImplTraitContext::disallowed(),
1107 // Destructure like a tuple struct.
1108 let tuple_struct_pat =
1109 hir::PatKind::TupleStruct(qpath, pats, rest.map(|r| r.0));
1110 return self.pat_without_dbm(lhs.span, tuple_struct_pat);
1114 ExprKind::Struct(se) => {
1115 let field_pats = self.arena.alloc_from_iter(se.fields.iter().map(|f| {
1116 let pat = self.destructure_assign(&f.expr, eq_sign_span, assignments);
1118 hir_id: self.next_id(),
1121 is_shorthand: f.is_shorthand,
1125 let qpath = self.lower_qpath(
1129 ParamMode::Optional,
1130 ImplTraitContext::disallowed(),
1132 let fields_omitted = match &se.rest {
1133 StructRest::Base(e) => {
1137 "functional record updates are not allowed in destructuring \
1142 "consider removing the trailing pattern",
1144 rustc_errors::Applicability::MachineApplicable,
1149 StructRest::Rest(_) => true,
1150 StructRest::None => false,
1152 let struct_pat = hir::PatKind::Struct(qpath, field_pats, fields_omitted);
1153 return self.pat_without_dbm(lhs.span, struct_pat);
1156 ExprKind::Tup(elements) => {
1158 self.destructure_sequence(elements, "tuple", eq_sign_span, assignments);
1159 let tuple_pat = hir::PatKind::Tuple(pats, rest.map(|r| r.0));
1160 return self.pat_without_dbm(lhs.span, tuple_pat);
1162 ExprKind::Paren(e) => {
1163 // We special-case `(..)` for consistency with patterns.
1164 if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
1165 let tuple_pat = hir::PatKind::Tuple(&[], Some(0));
1166 return self.pat_without_dbm(lhs.span, tuple_pat);
1168 return self.destructure_assign(e, eq_sign_span, assignments);
1173 // Treat all other cases as normal lvalue.
1174 let ident = Ident::new(sym::lhs, lhs.span);
1175 let (pat, binding) = self.pat_ident(lhs.span, ident);
1176 let ident = self.expr_ident(lhs.span, ident, binding);
1177 let assign = hir::ExprKind::Assign(self.lower_expr(lhs), ident, eq_sign_span);
1178 let expr = self.expr(lhs.span, assign, ThinVec::new());
1179 assignments.push(self.stmt_expr(lhs.span, expr));
1183 /// Destructure a sequence of expressions occurring on the LHS of an assignment.
1184 /// Such a sequence occurs in a tuple (struct)/slice.
1185 /// Return a sequence of corresponding patterns, and the index and the span of `..` if it
1187 /// Each sub-assignment is recorded in `assignments`.
1188 fn destructure_sequence(
1190 elements: &[AstP<Expr>],
1193 assignments: &mut Vec<hir::Stmt<'hir>>,
1194 ) -> (&'hir [&'hir hir::Pat<'hir>], Option<(usize, Span)>) {
1195 let mut rest = None;
1197 self.arena.alloc_from_iter(elements.iter().enumerate().filter_map(|(i, e)| {
1198 // Check for `..` pattern.
1199 if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
1200 if let Some((_, prev_span)) = rest {
1201 self.ban_extra_rest_pat(e.span, prev_span, ctx);
1203 rest = Some((i, e.span));
1207 Some(self.destructure_assign(e, eq_sign_span, assignments))
1213 /// Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`.
1214 fn lower_expr_range_closed(&mut self, span: Span, e1: &Expr, e2: &Expr) -> hir::ExprKind<'hir> {
1215 let e1 = self.lower_expr_mut(e1);
1216 let e2 = self.lower_expr_mut(e2);
1217 let fn_path = hir::QPath::LangItem(hir::LangItem::RangeInclusiveNew, span);
1219 self.arena.alloc(self.expr(span, hir::ExprKind::Path(fn_path), ThinVec::new()));
1220 hir::ExprKind::Call(fn_expr, arena_vec![self; e1, e2])
1223 fn lower_expr_range(
1229 ) -> hir::ExprKind<'hir> {
1230 use rustc_ast::RangeLimits::*;
1232 let lang_item = match (e1, e2, lims) {
1233 (None, None, HalfOpen) => hir::LangItem::RangeFull,
1234 (Some(..), None, HalfOpen) => hir::LangItem::RangeFrom,
1235 (None, Some(..), HalfOpen) => hir::LangItem::RangeTo,
1236 (Some(..), Some(..), HalfOpen) => hir::LangItem::Range,
1237 (None, Some(..), Closed) => hir::LangItem::RangeToInclusive,
1238 (Some(..), Some(..), Closed) => unreachable!(),
1239 (_, None, Closed) => self.diagnostic().span_fatal(span, "inclusive range with no end"),
1242 let fields = self.arena.alloc_from_iter(
1243 e1.iter().map(|e| ("start", e)).chain(e2.iter().map(|e| ("end", e))).map(|(s, e)| {
1244 let expr = self.lower_expr(&e);
1245 let ident = Ident::new(Symbol::intern(s), e.span);
1246 self.expr_field(ident, expr, e.span)
1250 hir::ExprKind::Struct(self.arena.alloc(hir::QPath::LangItem(lang_item, span)), fields, None)
1253 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
1254 let target_id = match destination {
1256 if let Some(loop_id) = self.resolver.get_label_res(id) {
1257 Ok(self.lower_node_id(loop_id))
1259 Err(hir::LoopIdError::UnresolvedLabel)
1266 .map(|id| Ok(self.lower_node_id(id)))
1267 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope)),
1269 hir::Destination { label: destination.map(|(_, label)| label), target_id }
1272 fn lower_jump_destination(&mut self, id: NodeId, opt_label: Option<Label>) -> hir::Destination {
1273 if self.is_in_loop_condition && opt_label.is_none() {
1276 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition),
1279 self.lower_loop_destination(opt_label.map(|label| (id, label)))
1283 fn with_catch_scope<T>(&mut self, catch_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1284 let len = self.catch_scopes.len();
1285 self.catch_scopes.push(catch_id);
1287 let result = f(self);
1290 self.catch_scopes.len(),
1291 "catch scopes should be added and removed in stack order"
1294 self.catch_scopes.pop().unwrap();
1299 fn with_loop_scope<T>(&mut self, loop_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1300 // We're no longer in the base loop's condition; we're in another loop.
1301 let was_in_loop_condition = self.is_in_loop_condition;
1302 self.is_in_loop_condition = false;
1304 let len = self.loop_scopes.len();
1305 self.loop_scopes.push(loop_id);
1307 let result = f(self);
1310 self.loop_scopes.len(),
1311 "loop scopes should be added and removed in stack order"
1314 self.loop_scopes.pop().unwrap();
1316 self.is_in_loop_condition = was_in_loop_condition;
1321 fn with_loop_condition_scope<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
1322 let was_in_loop_condition = self.is_in_loop_condition;
1323 self.is_in_loop_condition = true;
1325 let result = f(self);
1327 self.is_in_loop_condition = was_in_loop_condition;
1332 fn lower_expr_llvm_asm(&mut self, asm: &LlvmInlineAsm) -> hir::ExprKind<'hir> {
1333 let inner = hir::LlvmInlineAsmInner {
1334 inputs: asm.inputs.iter().map(|&(c, _)| c).collect(),
1338 .map(|out| hir::LlvmInlineAsmOutput {
1339 constraint: out.constraint,
1341 is_indirect: out.is_indirect,
1342 span: out.expr.span,
1346 asm_str_style: asm.asm_str_style,
1347 clobbers: asm.clobbers.clone(),
1348 volatile: asm.volatile,
1349 alignstack: asm.alignstack,
1350 dialect: asm.dialect,
1352 let hir_asm = hir::LlvmInlineAsm {
1354 inputs_exprs: self.arena.alloc_from_iter(
1355 asm.inputs.iter().map(|&(_, ref input)| self.lower_expr_mut(input)),
1359 .alloc_from_iter(asm.outputs.iter().map(|out| self.lower_expr_mut(&out.expr))),
1361 hir::ExprKind::LlvmInlineAsm(self.arena.alloc(hir_asm))
1364 fn lower_expr_field(&mut self, f: &ExprField) -> hir::ExprField<'hir> {
1366 hir_id: self.next_id(),
1368 expr: self.lower_expr(&f.expr),
1370 is_shorthand: f.is_shorthand,
1374 fn lower_expr_yield(&mut self, span: Span, opt_expr: Option<&Expr>) -> hir::ExprKind<'hir> {
1375 match self.generator_kind {
1376 Some(hir::GeneratorKind::Gen) => {}
1377 Some(hir::GeneratorKind::Async(_)) => {
1382 "`async` generators are not yet supported"
1386 None => self.generator_kind = Some(hir::GeneratorKind::Gen),
1390 opt_expr.as_ref().map(|x| self.lower_expr(x)).unwrap_or_else(|| self.expr_unit(span));
1392 hir::ExprKind::Yield(expr, hir::YieldSource::Yield)
1395 /// Desugar `ExprForLoop` from: `[opt_ident]: for <pat> in <head> <body>` into:
1398 /// let result = match ::std::iter::IntoIterator::into_iter(<head>) {
1400 /// [opt_ident]: loop {
1402 /// match ::std::iter::Iterator::next(&mut iter) {
1403 /// ::std::option::Option::Some(val) => __next = val,
1404 /// ::std::option::Option::None => break
1406 /// let <pat> = __next;
1407 /// StmtKind::Expr(<body>);
1420 opt_label: Option<Label>,
1421 ) -> hir::Expr<'hir> {
1422 let orig_head_span = head.span;
1424 let mut head = self.lower_expr_mut(head);
1425 let desugared_span = self.mark_span_with_reason(
1426 DesugaringKind::ForLoop(ForLoopLoc::Head),
1430 head.span = desugared_span;
1432 let iter = Ident::with_dummy_span(sym::iter);
1434 let next_ident = Ident::with_dummy_span(sym::__next);
1435 let (next_pat, next_pat_hid) = self.pat_ident_binding_mode(
1438 hir::BindingAnnotation::Mutable,
1441 // `::std::option::Option::Some(val) => __next = val`
1443 let val_ident = Ident::with_dummy_span(sym::val);
1444 let (val_pat, val_pat_hid) = self.pat_ident(pat.span, val_ident);
1445 let val_expr = self.expr_ident(pat.span, val_ident, val_pat_hid);
1446 let next_expr = self.expr_ident(pat.span, next_ident, next_pat_hid);
1447 let assign = self.arena.alloc(self.expr(
1449 hir::ExprKind::Assign(next_expr, val_expr, pat.span),
1452 let some_pat = self.pat_some(pat.span, val_pat);
1453 self.arm(some_pat, assign)
1456 // `::std::option::Option::None => break`
1459 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
1460 let pat = self.pat_none(e.span);
1461 self.arm(pat, break_expr)
1465 let (iter_pat, iter_pat_nid) =
1466 self.pat_ident_binding_mode(desugared_span, iter, hir::BindingAnnotation::Mutable);
1468 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
1470 let iter = self.expr_ident(desugared_span, iter, iter_pat_nid);
1471 let ref_mut_iter = self.expr_mut_addr_of(desugared_span, iter);
1472 let next_expr = self.expr_call_lang_item_fn(
1474 hir::LangItem::IteratorNext,
1475 arena_vec![self; ref_mut_iter],
1477 let arms = arena_vec![self; pat_arm, break_arm];
1479 self.expr_match(desugared_span, next_expr, arms, hir::MatchSource::ForLoopDesugar)
1481 let match_stmt = self.stmt_expr(desugared_span, match_expr);
1483 let next_expr = self.expr_ident(desugared_span, next_ident, next_pat_hid);
1486 let next_let = self.stmt_let_pat(
1491 hir::LocalSource::ForLoopDesugar,
1494 // `let <pat> = __next`
1495 let pat = self.lower_pat(pat);
1496 let pat_let = self.stmt_let_pat(
1501 hir::LocalSource::ForLoopDesugar,
1504 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
1505 let body_expr = self.expr_block(body_block, ThinVec::new());
1506 let body_stmt = self.stmt_expr(body.span, body_expr);
1508 let loop_block = self.block_all(
1510 arena_vec![self; next_let, match_stmt, pat_let, body_stmt],
1514 // `[opt_ident]: loop { ... }`
1515 let kind = hir::ExprKind::Loop(
1518 hir::LoopSource::ForLoop,
1519 e.span.with_hi(orig_head_span.hi()),
1522 self.arena.alloc(hir::Expr { hir_id: self.lower_node_id(e.id), kind, span: e.span });
1524 // `mut iter => { ... }`
1525 let iter_arm = self.arm(iter_pat, loop_expr);
1527 let into_iter_span = self.mark_span_with_reason(
1528 DesugaringKind::ForLoop(ForLoopLoc::IntoIter),
1533 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
1534 let into_iter_expr = {
1535 self.expr_call_lang_item_fn(
1537 hir::LangItem::IntoIterIntoIter,
1538 arena_vec![self; head],
1542 let match_expr = self.arena.alloc(self.expr_match(
1545 arena_vec![self; iter_arm],
1546 hir::MatchSource::ForLoopDesugar,
1549 let attrs: Vec<_> = e.attrs.iter().map(|a| self.lower_attr(a)).collect();
1551 // This is effectively `{ let _result = ...; _result }`.
1552 // The construct was introduced in #21984 and is necessary to make sure that
1553 // temporaries in the `head` expression are dropped and do not leak to the
1554 // surrounding scope of the `match` since the `match` is not a terminating scope.
1556 // Also, add the attributes to the outer returned expr node.
1557 self.expr_drop_temps_mut(desugared_span, match_expr, attrs.into())
1560 /// Desugar `ExprKind::Try` from: `<expr>?` into:
1562 /// match Try::into_result(<expr>) {
1563 /// Ok(val) => #[allow(unreachable_code)] val,
1564 /// Err(err) => #[allow(unreachable_code)]
1565 /// // If there is an enclosing `try {...}`:
1566 /// break 'catch_target Try::from_error(From::from(err)),
1568 /// return Try::from_error(From::from(err)),
1571 fn lower_expr_try(&mut self, span: Span, sub_expr: &Expr) -> hir::ExprKind<'hir> {
1572 let unstable_span = self.mark_span_with_reason(
1573 DesugaringKind::QuestionMark,
1575 self.allow_try_trait.clone(),
1577 let try_span = self.sess.source_map().end_point(span);
1578 let try_span = self.mark_span_with_reason(
1579 DesugaringKind::QuestionMark,
1581 self.allow_try_trait.clone(),
1584 // `Try::branch(<expr>)`
1587 let sub_expr = self.lower_expr_mut(sub_expr);
1589 self.expr_call_lang_item_fn(
1591 hir::LangItem::TryTraitBranch,
1592 arena_vec![self; sub_expr],
1596 // `#[allow(unreachable_code)]`
1598 // `allow(unreachable_code)`
1600 let allow_ident = Ident::new(sym::allow, span);
1601 let uc_ident = Ident::new(sym::unreachable_code, span);
1602 let uc_nested = attr::mk_nested_word_item(uc_ident);
1603 attr::mk_list_item(allow_ident, vec![uc_nested])
1605 attr::mk_attr_outer(allow)
1607 let attrs = vec![attr];
1609 // `ControlFlow::Continue(val) => #[allow(unreachable_code)] val,`
1610 let continue_arm = {
1611 let val_ident = Ident::with_dummy_span(sym::val);
1612 let (val_pat, val_pat_nid) = self.pat_ident(span, val_ident);
1613 let val_expr = self.arena.alloc(self.expr_ident_with_attrs(
1617 ThinVec::from(attrs.clone()),
1619 let continue_pat = self.pat_cf_continue(unstable_span, val_pat);
1620 self.arm(continue_pat, val_expr)
1623 // `ControlFlow::Break(residual) =>
1624 // #[allow(unreachable_code)]
1625 // return Try::from_residual(residual),`
1627 let residual_ident = Ident::with_dummy_span(sym::residual);
1628 let (residual_local, residual_local_nid) = self.pat_ident(try_span, residual_ident);
1629 let residual_expr = self.expr_ident_mut(try_span, residual_ident, residual_local_nid);
1630 let from_residual_expr = self.wrap_in_try_constructor(
1631 hir::LangItem::TryTraitFromResidual,
1633 self.arena.alloc(residual_expr),
1636 let thin_attrs = ThinVec::from(attrs);
1637 let catch_scope = self.catch_scopes.last().copied();
1638 let ret_expr = if let Some(catch_node) = catch_scope {
1639 let target_id = Ok(self.lower_node_id(catch_node));
1640 self.arena.alloc(self.expr(
1642 hir::ExprKind::Break(
1643 hir::Destination { label: None, target_id },
1644 Some(from_residual_expr),
1649 self.arena.alloc(self.expr(
1651 hir::ExprKind::Ret(Some(from_residual_expr)),
1656 let break_pat = self.pat_cf_break(try_span, residual_local);
1657 self.arm(break_pat, ret_expr)
1660 hir::ExprKind::Match(
1662 arena_vec![self; break_arm, continue_arm],
1663 hir::MatchSource::TryDesugar,
1667 // =========================================================================
1668 // Helper methods for building HIR.
1669 // =========================================================================
1671 /// Constructs a `true` or `false` literal expression.
1672 pub(super) fn expr_bool(&mut self, span: Span, val: bool) -> &'hir hir::Expr<'hir> {
1673 let lit = Spanned { span, node: LitKind::Bool(val) };
1674 self.arena.alloc(self.expr(span, hir::ExprKind::Lit(lit), ThinVec::new()))
1677 /// Wrap the given `expr` in a terminating scope using `hir::ExprKind::DropTemps`.
1679 /// In terms of drop order, it has the same effect as wrapping `expr` in
1680 /// `{ let _t = $expr; _t }` but should provide better compile-time performance.
1682 /// The drop order can be important in e.g. `if expr { .. }`.
1683 pub(super) fn expr_drop_temps(
1686 expr: &'hir hir::Expr<'hir>,
1688 ) -> &'hir hir::Expr<'hir> {
1689 self.arena.alloc(self.expr_drop_temps_mut(span, expr, attrs))
1692 pub(super) fn expr_drop_temps_mut(
1695 expr: &'hir hir::Expr<'hir>,
1697 ) -> hir::Expr<'hir> {
1698 self.expr(span, hir::ExprKind::DropTemps(expr), attrs)
1704 arg: &'hir hir::Expr<'hir>,
1705 arms: &'hir [hir::Arm<'hir>],
1706 source: hir::MatchSource,
1707 ) -> hir::Expr<'hir> {
1708 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
1711 fn expr_break(&mut self, span: Span, attrs: AttrVec) -> &'hir hir::Expr<'hir> {
1712 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
1713 self.arena.alloc(self.expr(span, expr_break, attrs))
1716 fn expr_mut_addr_of(&mut self, span: Span, e: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
1719 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Mut, e),
1724 fn expr_unit(&mut self, sp: Span) -> &'hir hir::Expr<'hir> {
1725 self.arena.alloc(self.expr(sp, hir::ExprKind::Tup(&[]), ThinVec::new()))
1731 e: &'hir hir::Expr<'hir>,
1732 args: &'hir [hir::Expr<'hir>],
1733 ) -> hir::Expr<'hir> {
1734 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
1740 e: &'hir hir::Expr<'hir>,
1741 args: &'hir [hir::Expr<'hir>],
1742 ) -> &'hir hir::Expr<'hir> {
1743 self.arena.alloc(self.expr_call_mut(span, e, args))
1746 fn expr_call_lang_item_fn_mut(
1749 lang_item: hir::LangItem,
1750 args: &'hir [hir::Expr<'hir>],
1751 ) -> hir::Expr<'hir> {
1752 let path = self.arena.alloc(self.expr_lang_item_path(span, lang_item, ThinVec::new()));
1753 self.expr_call_mut(span, path, args)
1756 fn expr_call_lang_item_fn(
1759 lang_item: hir::LangItem,
1760 args: &'hir [hir::Expr<'hir>],
1761 ) -> &'hir hir::Expr<'hir> {
1762 self.arena.alloc(self.expr_call_lang_item_fn_mut(span, lang_item, args))
1765 fn expr_lang_item_path(
1768 lang_item: hir::LangItem,
1770 ) -> hir::Expr<'hir> {
1771 self.expr(span, hir::ExprKind::Path(hir::QPath::LangItem(lang_item, span)), attrs)
1774 pub(super) fn expr_ident(
1778 binding: hir::HirId,
1779 ) -> &'hir hir::Expr<'hir> {
1780 self.arena.alloc(self.expr_ident_mut(sp, ident, binding))
1783 pub(super) fn expr_ident_mut(
1787 binding: hir::HirId,
1788 ) -> hir::Expr<'hir> {
1789 self.expr_ident_with_attrs(sp, ident, binding, ThinVec::new())
1792 fn expr_ident_with_attrs(
1796 binding: hir::HirId,
1798 ) -> hir::Expr<'hir> {
1799 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
1801 self.arena.alloc(hir::Path {
1803 res: Res::Local(binding),
1804 segments: arena_vec![self; hir::PathSegment::from_ident(ident)],
1808 self.expr(span, expr_path, attrs)
1811 fn expr_unsafe(&mut self, expr: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
1812 let hir_id = self.next_id();
1813 let span = expr.span;
1816 hir::ExprKind::Block(
1817 self.arena.alloc(hir::Block {
1821 rules: hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::CompilerGenerated),
1823 targeted_by_break: false,
1831 fn expr_block_empty(&mut self, span: Span) -> &'hir hir::Expr<'hir> {
1832 let blk = self.block_all(span, &[], None);
1833 let expr = self.expr_block(blk, ThinVec::new());
1834 self.arena.alloc(expr)
1837 pub(super) fn expr_block(
1839 b: &'hir hir::Block<'hir>,
1841 ) -> hir::Expr<'hir> {
1842 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
1848 kind: hir::ExprKind<'hir>,
1850 ) -> hir::Expr<'hir> {
1851 let hir_id = self.next_id();
1852 self.lower_attrs(hir_id, &attrs);
1853 hir::Expr { hir_id, kind, span }
1859 expr: &'hir hir::Expr<'hir>,
1861 ) -> hir::ExprField<'hir> {
1862 hir::ExprField { hir_id: self.next_id(), ident, span, expr, is_shorthand: false }
1865 fn arm(&mut self, pat: &'hir hir::Pat<'hir>, expr: &'hir hir::Expr<'hir>) -> hir::Arm<'hir> {
1866 hir::Arm { hir_id: self.next_id(), pat, guard: None, span: expr.span, body: expr }