2 AsyncGeneratorsNotSupported, AsyncNonMoveClosureNotSupported, AwaitOnlyInAsyncFnAndBlocks,
3 BaseExpressionDoubleDot, ClosureCannotBeStatic, FunctionalRecordUpdateDestructuringAssignemnt,
4 GeneratorTooManyParameters, InclusiveRangeWithNoEnd, NotSupportedForLifetimeBinderAsyncClosure,
5 RustcBoxAttributeError, UnderscoreExprLhsAssign,
7 use super::ResolverAstLoweringExt;
8 use super::{ImplTraitContext, LoweringContext, ParamMode, ParenthesizedGenericArgs};
9 use crate::{FnDeclKind, ImplTraitPosition};
11 use rustc_ast::ptr::P as AstP;
13 use rustc_data_structures::stack::ensure_sufficient_stack;
15 use rustc_hir::def::Res;
16 use rustc_hir::definitions::DefPathData;
17 use rustc_session::errors::report_lit_error;
18 use rustc_span::source_map::{respan, DesugaringKind, Span, Spanned};
19 use rustc_span::symbol::{sym, Ident};
20 use rustc_span::DUMMY_SP;
21 use thin_vec::thin_vec;
23 impl<'hir> LoweringContext<'_, 'hir> {
24 fn lower_exprs(&mut self, exprs: &[AstP<Expr>]) -> &'hir [hir::Expr<'hir>] {
25 self.arena.alloc_from_iter(exprs.iter().map(|x| self.lower_expr_mut(x)))
28 pub(super) fn lower_expr(&mut self, e: &Expr) -> &'hir hir::Expr<'hir> {
29 self.arena.alloc(self.lower_expr_mut(e))
32 pub(super) fn lower_expr_mut(&mut self, e: &Expr) -> hir::Expr<'hir> {
33 ensure_sufficient_stack(|| {
34 let kind = match e.kind {
35 ExprKind::Box(ref inner) => hir::ExprKind::Box(self.lower_expr(inner)),
36 ExprKind::Array(ref exprs) => hir::ExprKind::Array(self.lower_exprs(exprs)),
37 ExprKind::ConstBlock(ref anon_const) => {
38 let anon_const = self.lower_anon_const(anon_const);
39 hir::ExprKind::ConstBlock(anon_const)
41 ExprKind::Repeat(ref expr, ref count) => {
42 let expr = self.lower_expr(expr);
43 let count = self.lower_array_length(count);
44 hir::ExprKind::Repeat(expr, count)
46 ExprKind::Tup(ref elts) => hir::ExprKind::Tup(self.lower_exprs(elts)),
47 ExprKind::Call(ref f, ref args) => {
48 if e.attrs.get(0).map_or(false, |a| a.has_name(sym::rustc_box)) {
49 if let [inner] = &args[..] && e.attrs.len() == 1 {
50 let kind = hir::ExprKind::Box(self.lower_expr(&inner));
51 let hir_id = self.lower_node_id(e.id);
52 return hir::Expr { hir_id, kind, span: self.lower_span(e.span) };
54 self.tcx.sess.emit_err(RustcBoxAttributeError { span: e.span });
57 } else if let Some(legacy_args) = self.resolver.legacy_const_generic_args(f) {
58 self.lower_legacy_const_generics((**f).clone(), args.clone(), &legacy_args)
60 let f = self.lower_expr(f);
61 hir::ExprKind::Call(f, self.lower_exprs(args))
64 ExprKind::MethodCall(box MethodCall { ref seg, ref receiver, ref args, span }) => {
65 let hir_seg = self.arena.alloc(self.lower_path_segment(
69 ParenthesizedGenericArgs::Err,
70 &ImplTraitContext::Disallowed(ImplTraitPosition::Path),
72 let receiver = self.lower_expr(receiver);
74 self.arena.alloc_from_iter(args.iter().map(|x| self.lower_expr_mut(x)));
75 hir::ExprKind::MethodCall(hir_seg, receiver, args, self.lower_span(span))
77 ExprKind::Binary(binop, ref lhs, ref rhs) => {
78 let binop = self.lower_binop(binop);
79 let lhs = self.lower_expr(lhs);
80 let rhs = self.lower_expr(rhs);
81 hir::ExprKind::Binary(binop, lhs, rhs)
83 ExprKind::Unary(op, ref ohs) => {
84 let op = self.lower_unop(op);
85 let ohs = self.lower_expr(ohs);
86 hir::ExprKind::Unary(op, ohs)
88 ExprKind::Lit(token_lit) => {
89 let lit_kind = match LitKind::from_token_lit(token_lit) {
90 Ok(lit_kind) => lit_kind,
92 report_lit_error(&self.tcx.sess.parse_sess, err, token_lit, e.span);
96 hir::ExprKind::Lit(respan(self.lower_span(e.span), lit_kind))
98 ExprKind::IncludedBytes(ref bytes) => hir::ExprKind::Lit(respan(
99 self.lower_span(e.span),
100 LitKind::ByteStr(bytes.clone()),
102 ExprKind::Cast(ref expr, ref ty) => {
103 let expr = self.lower_expr(expr);
105 self.lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
106 hir::ExprKind::Cast(expr, ty)
108 ExprKind::Type(ref expr, ref ty) => {
109 let expr = self.lower_expr(expr);
111 self.lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::Type));
112 hir::ExprKind::Type(expr, ty)
114 ExprKind::AddrOf(k, m, ref ohs) => {
115 let ohs = self.lower_expr(ohs);
116 hir::ExprKind::AddrOf(k, m, ohs)
118 ExprKind::Let(ref pat, ref scrutinee, span) => {
119 hir::ExprKind::Let(self.arena.alloc(hir::Let {
120 hir_id: self.next_id(),
121 span: self.lower_span(span),
122 pat: self.lower_pat(pat),
124 init: self.lower_expr(scrutinee),
127 ExprKind::If(ref cond, ref then, ref else_opt) => {
128 self.lower_expr_if(cond, then, else_opt.as_deref())
130 ExprKind::While(ref cond, ref body, opt_label) => {
131 self.with_loop_scope(e.id, |this| {
133 this.mark_span_with_reason(DesugaringKind::WhileLoop, e.span, None);
134 this.lower_expr_while_in_loop_scope(span, cond, body, opt_label)
137 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
139 this.lower_block(body, false),
140 this.lower_label(opt_label),
141 hir::LoopSource::Loop,
145 ExprKind::TryBlock(ref body) => self.lower_expr_try_block(body),
146 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
147 self.lower_expr(expr),
148 self.arena.alloc_from_iter(arms.iter().map(|x| self.lower_arm(x))),
149 hir::MatchSource::Normal,
151 ExprKind::Async(capture_clause, closure_node_id, ref block) => self
157 hir::AsyncGeneratorKind::Block,
158 |this| this.with_new_scopes(|this| this.lower_block_expr(block)),
160 ExprKind::Await(ref expr) => {
161 let dot_await_span = if expr.span.hi() < e.span.hi() {
162 let span_with_whitespace = self
166 .span_extend_while(expr.span, char::is_whitespace)
167 .unwrap_or(expr.span);
168 span_with_whitespace.shrink_to_hi().with_hi(e.span.hi())
170 // this is a recovered `await expr`
173 self.lower_expr_await(dot_await_span, expr)
175 ExprKind::Closure(box Closure {
184 if let Async::Yes { closure_id, .. } = asyncness {
185 self.lower_expr_async_closure(
195 self.lower_expr_closure(
206 ExprKind::Block(ref blk, opt_label) => {
207 let opt_label = self.lower_label(opt_label);
208 hir::ExprKind::Block(self.lower_block(blk, opt_label.is_some()), opt_label)
210 ExprKind::Assign(ref el, ref er, span) => {
211 self.lower_expr_assign(el, er, span, e.span)
213 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
214 self.lower_binop(op),
218 ExprKind::Field(ref el, ident) => {
219 hir::ExprKind::Field(self.lower_expr(el), self.lower_ident(ident))
221 ExprKind::Index(ref el, ref er) => {
222 hir::ExprKind::Index(self.lower_expr(el), self.lower_expr(er))
224 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
225 self.lower_expr_range_closed(e.span, e1, e2)
227 ExprKind::Range(ref e1, ref e2, lims) => {
228 self.lower_expr_range(e.span, e1.as_deref(), e2.as_deref(), lims)
230 ExprKind::Underscore => {
231 self.tcx.sess.emit_err(UnderscoreExprLhsAssign { span: e.span });
234 ExprKind::Path(ref qself, ref path) => {
235 let qpath = self.lower_qpath(
240 &ImplTraitContext::Disallowed(ImplTraitPosition::Path),
242 hir::ExprKind::Path(qpath)
244 ExprKind::Break(opt_label, ref opt_expr) => {
245 let opt_expr = opt_expr.as_ref().map(|x| self.lower_expr(x));
246 hir::ExprKind::Break(self.lower_jump_destination(e.id, opt_label), opt_expr)
248 ExprKind::Continue(opt_label) => {
249 hir::ExprKind::Continue(self.lower_jump_destination(e.id, opt_label))
251 ExprKind::Ret(ref e) => {
252 let e = e.as_ref().map(|x| self.lower_expr(x));
253 hir::ExprKind::Ret(e)
255 ExprKind::Yeet(ref sub_expr) => self.lower_expr_yeet(e.span, sub_expr.as_deref()),
256 ExprKind::InlineAsm(ref asm) => {
257 hir::ExprKind::InlineAsm(self.lower_inline_asm(e.span, asm))
259 ExprKind::Struct(ref se) => {
260 let rest = match &se.rest {
261 StructRest::Base(e) => Some(self.lower_expr(e)),
262 StructRest::Rest(sp) => {
263 self.tcx.sess.emit_err(BaseExpressionDoubleDot { span: *sp });
264 Some(&*self.arena.alloc(self.expr_err(*sp)))
266 StructRest::None => None,
268 hir::ExprKind::Struct(
269 self.arena.alloc(self.lower_qpath(
274 &ImplTraitContext::Disallowed(ImplTraitPosition::Path),
277 .alloc_from_iter(se.fields.iter().map(|x| self.lower_expr_field(x))),
281 ExprKind::Yield(ref opt_expr) => self.lower_expr_yield(e.span, opt_expr.as_deref()),
282 ExprKind::Err => hir::ExprKind::Err,
283 ExprKind::Try(ref sub_expr) => self.lower_expr_try(e.span, sub_expr),
284 ExprKind::Paren(ref ex) => {
285 let mut ex = self.lower_expr_mut(ex);
286 // Include parens in span, but only if it is a super-span.
287 if e.span.contains(ex.span) {
288 ex.span = self.lower_span(e.span);
290 // Merge attributes into the inner expression.
291 if !e.attrs.is_empty() {
293 self.attrs.get(&ex.hir_id.local_id).map(|la| *la).unwrap_or(&[]);
296 &*self.arena.alloc_from_iter(
299 .map(|a| self.lower_attr(a))
300 .chain(old_attrs.iter().cloned()),
307 // Desugar `ExprForLoop`
308 // from: `[opt_ident]: for <pat> in <head> <body>`
309 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
310 return self.lower_expr_for(e, pat, head, body, opt_label);
312 ExprKind::MacCall(_) => panic!("{:?} shouldn't exist here", e.span),
315 let hir_id = self.lower_node_id(e.id);
316 self.lower_attrs(hir_id, &e.attrs);
317 hir::Expr { hir_id, kind, span: self.lower_span(e.span) }
321 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
323 UnOp::Deref => hir::UnOp::Deref,
324 UnOp::Not => hir::UnOp::Not,
325 UnOp::Neg => hir::UnOp::Neg,
329 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
332 BinOpKind::Add => hir::BinOpKind::Add,
333 BinOpKind::Sub => hir::BinOpKind::Sub,
334 BinOpKind::Mul => hir::BinOpKind::Mul,
335 BinOpKind::Div => hir::BinOpKind::Div,
336 BinOpKind::Rem => hir::BinOpKind::Rem,
337 BinOpKind::And => hir::BinOpKind::And,
338 BinOpKind::Or => hir::BinOpKind::Or,
339 BinOpKind::BitXor => hir::BinOpKind::BitXor,
340 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
341 BinOpKind::BitOr => hir::BinOpKind::BitOr,
342 BinOpKind::Shl => hir::BinOpKind::Shl,
343 BinOpKind::Shr => hir::BinOpKind::Shr,
344 BinOpKind::Eq => hir::BinOpKind::Eq,
345 BinOpKind::Lt => hir::BinOpKind::Lt,
346 BinOpKind::Le => hir::BinOpKind::Le,
347 BinOpKind::Ne => hir::BinOpKind::Ne,
348 BinOpKind::Ge => hir::BinOpKind::Ge,
349 BinOpKind::Gt => hir::BinOpKind::Gt,
351 span: self.lower_span(b.span),
355 fn lower_legacy_const_generics(
358 args: Vec<AstP<Expr>>,
359 legacy_args_idx: &[usize],
360 ) -> hir::ExprKind<'hir> {
361 let ExprKind::Path(None, ref mut path) = f.kind else {
365 // Split the arguments into const generics and normal arguments
366 let mut real_args = vec![];
367 let mut generic_args = vec![];
368 for (idx, arg) in args.into_iter().enumerate() {
369 if legacy_args_idx.contains(&idx) {
370 let parent_def_id = self.current_hir_id_owner;
371 let node_id = self.next_node_id();
373 // Add a definition for the in-band const def.
374 self.create_def(parent_def_id.def_id, node_id, DefPathData::AnonConst);
376 let anon_const = AnonConst { id: node_id, value: arg };
377 generic_args.push(AngleBracketedArg::Arg(GenericArg::Const(anon_const)));
383 // Add generic args to the last element of the path.
384 let last_segment = path.segments.last_mut().unwrap();
385 assert!(last_segment.args.is_none());
386 last_segment.args = Some(AstP(GenericArgs::AngleBracketed(AngleBracketedArgs {
391 // Now lower everything as normal.
392 let f = self.lower_expr(&f);
393 hir::ExprKind::Call(f, self.lower_exprs(&real_args))
400 else_opt: Option<&Expr>,
401 ) -> hir::ExprKind<'hir> {
402 let lowered_cond = self.lower_cond(cond);
403 let then_expr = self.lower_block_expr(then);
404 if let Some(rslt) = else_opt {
407 self.arena.alloc(then_expr),
408 Some(self.lower_expr(rslt)),
411 hir::ExprKind::If(lowered_cond, self.arena.alloc(then_expr), None)
415 // Lowers a condition (i.e. `cond` in `if cond` or `while cond`), wrapping it in a terminating scope
416 // so that temporaries created in the condition don't live beyond it.
417 fn lower_cond(&mut self, cond: &Expr) -> &'hir hir::Expr<'hir> {
418 fn has_let_expr(expr: &Expr) -> bool {
420 ExprKind::Binary(_, lhs, rhs) => has_let_expr(lhs) || has_let_expr(rhs),
421 ExprKind::Let(..) => true,
426 // We have to take special care for `let` exprs in the condition, e.g. in
427 // `if let pat = val` or `if foo && let pat = val`, as we _do_ want `val` to live beyond the
428 // condition in this case.
430 // In order to mantain the drop behavior for the non `let` parts of the condition,
431 // we still wrap them in terminating scopes, e.g. `if foo && let pat = val` essentially
432 // gets transformed into `if { let _t = foo; _t } && let pat = val`
434 ExprKind::Binary(op @ Spanned { node: ast::BinOpKind::And, .. }, lhs, rhs)
435 if has_let_expr(cond) =>
437 let op = self.lower_binop(*op);
438 let lhs = self.lower_cond(lhs);
439 let rhs = self.lower_cond(rhs);
441 self.arena.alloc(self.expr(
443 hir::ExprKind::Binary(op, lhs, rhs),
447 ExprKind::Let(..) => self.lower_expr(cond),
449 let cond = self.lower_expr(cond);
450 let reason = DesugaringKind::CondTemporary;
451 let span_block = self.mark_span_with_reason(reason, cond.span, None);
452 self.expr_drop_temps(span_block, cond, AttrVec::new())
457 // We desugar: `'label: while $cond $body` into:
461 // if { let _t = $cond; _t } {
470 // Wrap in a construct equivalent to `{ let _t = $cond; _t }`
471 // to preserve drop semantics since `while $cond { ... }` does not
472 // let temporaries live outside of `cond`.
473 fn lower_expr_while_in_loop_scope(
478 opt_label: Option<Label>,
479 ) -> hir::ExprKind<'hir> {
480 let lowered_cond = self.with_loop_condition_scope(|t| t.lower_cond(cond));
481 let then = self.lower_block_expr(body);
482 let expr_break = self.expr_break(span, AttrVec::new());
483 let stmt_break = self.stmt_expr(span, expr_break);
484 let else_blk = self.block_all(span, arena_vec![self; stmt_break], None);
485 let else_expr = self.arena.alloc(self.expr_block(else_blk, AttrVec::new()));
486 let if_kind = hir::ExprKind::If(lowered_cond, self.arena.alloc(then), Some(else_expr));
487 let if_expr = self.expr(span, if_kind, AttrVec::new());
488 let block = self.block_expr(self.arena.alloc(if_expr));
489 let span = self.lower_span(span.with_hi(cond.span.hi()));
490 let opt_label = self.lower_label(opt_label);
491 hir::ExprKind::Loop(block, opt_label, hir::LoopSource::While, span)
494 /// Desugar `try { <stmts>; <expr> }` into `{ <stmts>; ::std::ops::Try::from_output(<expr>) }`,
495 /// `try { <stmts>; }` into `{ <stmts>; ::std::ops::Try::from_output(()) }`
496 /// and save the block id to use it as a break target for desugaring of the `?` operator.
497 fn lower_expr_try_block(&mut self, body: &Block) -> hir::ExprKind<'hir> {
498 self.with_catch_scope(body.id, |this| {
499 let mut block = this.lower_block_noalloc(body, true);
501 // Final expression of the block (if present) or `()` with span at the end of block
502 let (try_span, tail_expr) = if let Some(expr) = block.expr.take() {
504 this.mark_span_with_reason(
505 DesugaringKind::TryBlock,
507 this.allow_try_trait.clone(),
512 let try_span = this.mark_span_with_reason(
513 DesugaringKind::TryBlock,
514 this.tcx.sess.source_map().end_point(body.span),
515 this.allow_try_trait.clone(),
518 (try_span, this.expr_unit(try_span))
521 let ok_wrapped_span =
522 this.mark_span_with_reason(DesugaringKind::TryBlock, tail_expr.span, None);
524 // `::std::ops::Try::from_output($tail_expr)`
525 block.expr = Some(this.wrap_in_try_constructor(
526 hir::LangItem::TryTraitFromOutput,
532 hir::ExprKind::Block(this.arena.alloc(block), None)
536 fn wrap_in_try_constructor(
538 lang_item: hir::LangItem,
540 expr: &'hir hir::Expr<'hir>,
542 ) -> &'hir hir::Expr<'hir> {
543 let constructor = self.arena.alloc(self.expr_lang_item_path(
549 self.expr_call(overall_span, constructor, std::slice::from_ref(expr))
552 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm<'hir> {
553 let pat = self.lower_pat(&arm.pat);
554 let guard = arm.guard.as_ref().map(|cond| {
555 if let ExprKind::Let(ref pat, ref scrutinee, span) = cond.kind {
556 hir::Guard::IfLet(self.arena.alloc(hir::Let {
557 hir_id: self.next_id(),
558 span: self.lower_span(span),
559 pat: self.lower_pat(pat),
561 init: self.lower_expr(scrutinee),
564 hir::Guard::If(self.lower_expr(cond))
567 let hir_id = self.next_id();
568 self.lower_attrs(hir_id, &arm.attrs);
573 body: self.lower_expr(&arm.body),
574 span: self.lower_span(arm.span),
578 /// Lower an `async` construct to a generator that is then wrapped so it implements `Future`.
583 /// std::future::from_generator(static move? |_task_context| -> <ret_ty> {
587 pub(super) fn make_async_expr(
589 capture_clause: CaptureBy,
590 closure_node_id: NodeId,
591 ret_ty: Option<AstP<Ty>>,
593 async_gen_kind: hir::AsyncGeneratorKind,
594 body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
595 ) -> hir::ExprKind<'hir> {
596 let output = match ret_ty {
597 Some(ty) => hir::FnRetTy::Return(
598 self.lower_ty(&ty, &ImplTraitContext::Disallowed(ImplTraitPosition::AsyncBlock)),
600 None => hir::FnRetTy::DefaultReturn(self.lower_span(span)),
603 // Resume argument type. We let the compiler infer this to simplify the lowering. It is
604 // fully constrained by `future::from_generator`.
605 let input_ty = hir::Ty {
606 hir_id: self.next_id(),
607 kind: hir::TyKind::Infer,
608 span: self.lower_span(span),
611 // The closure/generator `FnDecl` takes a single (resume) argument of type `input_ty`.
612 let fn_decl = self.arena.alloc(hir::FnDecl {
613 inputs: arena_vec![self; input_ty],
616 implicit_self: hir::ImplicitSelfKind::None,
619 // Lower the argument pattern/ident. The ident is used again in the `.await` lowering.
620 let (pat, task_context_hid) = self.pat_ident_binding_mode(
622 Ident::with_dummy_span(sym::_task_context),
623 hir::BindingAnnotation::MUT,
625 let param = hir::Param {
626 hir_id: self.next_id(),
628 ty_span: self.lower_span(span),
629 span: self.lower_span(span),
631 let params = arena_vec![self; param];
633 let body = self.lower_body(move |this| {
634 this.generator_kind = Some(hir::GeneratorKind::Async(async_gen_kind));
636 let old_ctx = this.task_context;
637 this.task_context = Some(task_context_hid);
638 let res = body(this);
639 this.task_context = old_ctx;
643 // `static |_task_context| -> <ret_ty> { body }`:
644 let generator_kind = {
645 let c = self.arena.alloc(hir::Closure {
646 def_id: self.local_def_id(closure_node_id),
647 binder: hir::ClosureBinder::Default,
649 bound_generic_params: &[],
652 fn_decl_span: self.lower_span(span),
653 movability: Some(hir::Movability::Static),
656 hir::ExprKind::Closure(c)
658 let parent_has_track_caller = self
661 .find(|attrs| attrs.into_iter().find(|attr| attr.has_name(sym::track_caller)).is_some())
664 self.mark_span_with_reason(DesugaringKind::Async, span, self.allow_gen_future.clone());
666 let hir_id = if parent_has_track_caller {
667 let generator_hir_id = self.lower_node_id(closure_node_id);
671 kind: AttrKind::Normal(ptr::P(NormalAttr {
673 path: Path::from_ident(Ident::new(sym::track_caller, span)),
674 args: MacArgs::Empty,
679 id: self.tcx.sess.parse_sess.attr_id_generator.mk_attr_id(),
680 style: AttrStyle::Outer,
686 self.lower_node_id(closure_node_id)
689 let generator = hir::Expr { hir_id, kind: generator_kind, span: self.lower_span(span) };
691 // `future::from_generator`:
692 let gen_future = self.expr_lang_item_path(
694 hir::LangItem::FromGenerator,
699 // `future::from_generator(generator)`:
700 hir::ExprKind::Call(self.arena.alloc(gen_future), arena_vec![self; generator])
703 /// Desugar `<expr>.await` into:
704 /// ```ignore (pseudo-rust)
705 /// match ::std::future::IntoFuture::into_future(<expr>) {
706 /// mut __awaitee => loop {
707 /// match unsafe { ::std::future::Future::poll(
708 /// <::std::pin::Pin>::new_unchecked(&mut __awaitee),
709 /// ::std::future::get_context(task_context),
711 /// ::std::task::Poll::Ready(result) => break result,
712 /// ::std::task::Poll::Pending => {}
714 /// task_context = yield ();
718 fn lower_expr_await(&mut self, dot_await_span: Span, expr: &Expr) -> hir::ExprKind<'hir> {
719 let full_span = expr.span.to(dot_await_span);
720 match self.generator_kind {
721 Some(hir::GeneratorKind::Async(_)) => {}
722 Some(hir::GeneratorKind::Gen) | None => {
723 self.tcx.sess.emit_err(AwaitOnlyInAsyncFnAndBlocks {
725 item_span: self.current_item,
729 let span = self.mark_span_with_reason(DesugaringKind::Await, dot_await_span, None);
730 let gen_future_span = self.mark_span_with_reason(
731 DesugaringKind::Await,
733 self.allow_gen_future.clone(),
735 let expr = self.lower_expr_mut(expr);
736 let expr_hir_id = expr.hir_id;
738 // Note that the name of this binding must not be changed to something else because
739 // debuggers and debugger extensions expect it to be called `__awaitee`. They use
740 // this name to identify what is being awaited by a suspended async functions.
741 let awaitee_ident = Ident::with_dummy_span(sym::__awaitee);
742 let (awaitee_pat, awaitee_pat_hid) =
743 self.pat_ident_binding_mode(span, awaitee_ident, hir::BindingAnnotation::MUT);
745 let task_context_ident = Ident::with_dummy_span(sym::_task_context);
748 // ::std::future::Future::poll(
749 // ::std::pin::Pin::new_unchecked(&mut __awaitee),
750 // ::std::future::get_context(task_context),
754 let awaitee = self.expr_ident(span, awaitee_ident, awaitee_pat_hid);
755 let ref_mut_awaitee = self.expr_mut_addr_of(span, awaitee);
756 let task_context = if let Some(task_context_hid) = self.task_context {
757 self.expr_ident_mut(span, task_context_ident, task_context_hid)
759 // Use of `await` outside of an async context, we cannot use `task_context` here.
762 let new_unchecked = self.expr_call_lang_item_fn_mut(
764 hir::LangItem::PinNewUnchecked,
765 arena_vec![self; ref_mut_awaitee],
768 let get_context = self.expr_call_lang_item_fn_mut(
770 hir::LangItem::GetContext,
771 arena_vec![self; task_context],
774 let call = self.expr_call_lang_item_fn(
776 hir::LangItem::FuturePoll,
777 arena_vec![self; new_unchecked, get_context],
780 self.arena.alloc(self.expr_unsafe(call))
783 // `::std::task::Poll::Ready(result) => break result`
784 let loop_node_id = self.next_node_id();
785 let loop_hir_id = self.lower_node_id(loop_node_id);
787 let x_ident = Ident::with_dummy_span(sym::result);
788 let (x_pat, x_pat_hid) = self.pat_ident(gen_future_span, x_ident);
789 let x_expr = self.expr_ident(gen_future_span, x_ident, x_pat_hid);
790 let ready_field = self.single_pat_field(gen_future_span, x_pat);
791 let ready_pat = self.pat_lang_item_variant(
793 hir::LangItem::PollReady,
797 let break_x = self.with_loop_scope(loop_node_id, move |this| {
799 hir::ExprKind::Break(this.lower_loop_destination(None), Some(x_expr));
800 this.arena.alloc(this.expr(gen_future_span, expr_break, AttrVec::new()))
802 self.arm(ready_pat, break_x)
805 // `::std::task::Poll::Pending => {}`
807 let pending_pat = self.pat_lang_item_variant(
809 hir::LangItem::PollPending,
813 let empty_block = self.expr_block_empty(span);
814 self.arm(pending_pat, empty_block)
817 let inner_match_stmt = {
818 let match_expr = self.expr_match(
821 arena_vec![self; ready_arm, pending_arm],
822 hir::MatchSource::AwaitDesugar,
824 self.stmt_expr(span, match_expr)
827 // task_context = yield ();
829 let unit = self.expr_unit(span);
830 let yield_expr = self.expr(
832 hir::ExprKind::Yield(unit, hir::YieldSource::Await { expr: Some(expr_hir_id) }),
835 let yield_expr = self.arena.alloc(yield_expr);
837 if let Some(task_context_hid) = self.task_context {
838 let lhs = self.expr_ident(span, task_context_ident, task_context_hid);
839 let assign = self.expr(
841 hir::ExprKind::Assign(lhs, yield_expr, self.lower_span(span)),
844 self.stmt_expr(span, assign)
846 // Use of `await` outside of an async context. Return `yield_expr` so that we can
847 // proceed with type checking.
848 self.stmt(span, hir::StmtKind::Semi(yield_expr))
852 let loop_block = self.block_all(span, arena_vec![self; inner_match_stmt, yield_stmt], None);
855 let loop_expr = self.arena.alloc(hir::Expr {
857 kind: hir::ExprKind::Loop(
860 hir::LoopSource::Loop,
861 self.lower_span(span),
863 span: self.lower_span(span),
866 // mut __awaitee => loop { ... }
867 let awaitee_arm = self.arm(awaitee_pat, loop_expr);
869 // `match ::std::future::IntoFuture::into_future(<expr>) { ... }`
870 let into_future_span = self.mark_span_with_reason(
871 DesugaringKind::Await,
873 self.allow_into_future.clone(),
875 let into_future_expr = self.expr_call_lang_item_fn(
877 hir::LangItem::IntoFutureIntoFuture,
878 arena_vec![self; expr],
882 // match <into_future_expr> {
883 // mut __awaitee => loop { .. }
885 hir::ExprKind::Match(
887 arena_vec![self; awaitee_arm],
888 hir::MatchSource::AwaitDesugar,
892 fn lower_expr_closure(
894 binder: &ClosureBinder,
895 capture_clause: CaptureBy,
897 movability: Movability,
901 ) -> hir::ExprKind<'hir> {
902 let (binder_clause, generic_params) = self.lower_closure_binder(binder);
904 let (body_id, generator_option) = self.with_new_scopes(move |this| {
905 let prev = this.current_item;
906 this.current_item = Some(fn_decl_span);
907 let mut generator_kind = None;
908 let body_id = this.lower_fn_body(decl, |this| {
909 let e = this.lower_expr_mut(body);
910 generator_kind = this.generator_kind;
913 let generator_option =
914 this.generator_movability_for_fn(&decl, fn_decl_span, generator_kind, movability);
915 this.current_item = prev;
916 (body_id, generator_option)
919 let bound_generic_params = self.lower_lifetime_binder(closure_id, generic_params);
920 // Lower outside new scope to preserve `is_in_loop_condition`.
921 let fn_decl = self.lower_fn_decl(decl, None, fn_decl_span, FnDeclKind::Closure, None);
923 let c = self.arena.alloc(hir::Closure {
924 def_id: self.local_def_id(closure_id),
925 binder: binder_clause,
927 bound_generic_params,
930 fn_decl_span: self.lower_span(fn_decl_span),
931 movability: generator_option,
934 hir::ExprKind::Closure(c)
937 fn generator_movability_for_fn(
941 generator_kind: Option<hir::GeneratorKind>,
942 movability: Movability,
943 ) -> Option<hir::Movability> {
944 match generator_kind {
945 Some(hir::GeneratorKind::Gen) => {
946 if decl.inputs.len() > 1 {
947 self.tcx.sess.emit_err(GeneratorTooManyParameters { fn_decl_span });
951 Some(hir::GeneratorKind::Async(_)) => {
952 panic!("non-`async` closure body turned `async` during lowering");
955 if movability == Movability::Static {
956 self.tcx.sess.emit_err(ClosureCannotBeStatic { fn_decl_span });
963 fn lower_closure_binder<'c>(
965 binder: &'c ClosureBinder,
966 ) -> (hir::ClosureBinder, &'c [GenericParam]) {
967 let (binder, params) = match binder {
968 ClosureBinder::NotPresent => (hir::ClosureBinder::Default, &[][..]),
969 &ClosureBinder::For { span, ref generic_params } => {
970 let span = self.lower_span(span);
971 (hir::ClosureBinder::For { span }, &**generic_params)
978 fn lower_expr_async_closure(
980 binder: &ClosureBinder,
981 capture_clause: CaptureBy,
983 inner_closure_id: NodeId,
987 ) -> hir::ExprKind<'hir> {
988 if let &ClosureBinder::For { span, .. } = binder {
989 self.tcx.sess.emit_err(NotSupportedForLifetimeBinderAsyncClosure { span });
992 let (binder_clause, generic_params) = self.lower_closure_binder(binder);
995 FnDecl { inputs: decl.inputs.clone(), output: FnRetTy::Default(fn_decl_span) };
997 let body = self.with_new_scopes(|this| {
998 // FIXME(cramertj): allow `async` non-`move` closures with arguments.
999 if capture_clause == CaptureBy::Ref && !decl.inputs.is_empty() {
1000 this.tcx.sess.emit_err(AsyncNonMoveClosureNotSupported { fn_decl_span });
1003 // Transform `async |x: u8| -> X { ... }` into
1004 // `|x: u8| future_from_generator(|| -> X { ... })`.
1005 let body_id = this.lower_fn_body(&outer_decl, |this| {
1007 if let FnRetTy::Ty(ty) = &decl.output { Some(ty.clone()) } else { None };
1008 let async_body = this.make_async_expr(
1013 hir::AsyncGeneratorKind::Closure,
1014 |this| this.with_new_scopes(|this| this.lower_expr_mut(body)),
1016 this.expr(fn_decl_span, async_body, AttrVec::new())
1021 let bound_generic_params = self.lower_lifetime_binder(closure_id, generic_params);
1022 // We need to lower the declaration outside the new scope, because we
1023 // have to conserve the state of being inside a loop condition for the
1024 // closure argument types.
1026 self.lower_fn_decl(&outer_decl, None, fn_decl_span, FnDeclKind::Closure, None);
1028 let c = self.arena.alloc(hir::Closure {
1029 def_id: self.local_def_id(closure_id),
1030 binder: binder_clause,
1032 bound_generic_params,
1035 fn_decl_span: self.lower_span(fn_decl_span),
1038 hir::ExprKind::Closure(c)
1041 /// Destructure the LHS of complex assignments.
1042 /// For instance, lower `(a, b) = t` to `{ let (lhs1, lhs2) = t; a = lhs1; b = lhs2; }`.
1043 fn lower_expr_assign(
1049 ) -> hir::ExprKind<'hir> {
1050 // Return early in case of an ordinary assignment.
1051 fn is_ordinary(lower_ctx: &mut LoweringContext<'_, '_>, lhs: &Expr) -> bool {
1054 | ExprKind::Struct(..)
1056 | ExprKind::Underscore => false,
1057 // Check for tuple struct constructor.
1058 ExprKind::Call(callee, ..) => lower_ctx.extract_tuple_struct_path(callee).is_none(),
1059 ExprKind::Paren(e) => {
1061 // We special-case `(..)` for consistency with patterns.
1062 ExprKind::Range(None, None, RangeLimits::HalfOpen) => false,
1063 _ => is_ordinary(lower_ctx, e),
1069 if is_ordinary(self, lhs) {
1070 return hir::ExprKind::Assign(
1071 self.lower_expr(lhs),
1072 self.lower_expr(rhs),
1073 self.lower_span(eq_sign_span),
1077 let mut assignments = vec![];
1079 // The LHS becomes a pattern: `(lhs1, lhs2)`.
1080 let pat = self.destructure_assign(lhs, eq_sign_span, &mut assignments);
1081 let rhs = self.lower_expr(rhs);
1083 // Introduce a `let` for destructuring: `let (lhs1, lhs2) = t`.
1084 let destructure_let = self.stmt_let_pat(
1089 hir::LocalSource::AssignDesugar(self.lower_span(eq_sign_span)),
1092 // `a = lhs1; b = lhs2;`.
1095 .alloc_from_iter(std::iter::once(destructure_let).chain(assignments.into_iter()));
1097 // Wrap everything in a block.
1098 hir::ExprKind::Block(&self.block_all(whole_span, stmts, None), None)
1101 /// If the given expression is a path to a tuple struct, returns that path.
1102 /// It is not a complete check, but just tries to reject most paths early
1103 /// if they are not tuple structs.
1104 /// Type checking will take care of the full validation later.
1105 fn extract_tuple_struct_path<'a>(
1108 ) -> Option<(&'a Option<AstP<QSelf>>, &'a Path)> {
1109 if let ExprKind::Path(qself, path) = &expr.kind {
1110 // Does the path resolve to something disallowed in a tuple struct/variant pattern?
1111 if let Some(partial_res) = self.resolver.get_partial_res(expr.id) {
1112 if let Some(res) = partial_res.full_res() && !res.expected_in_tuple_struct_pat() {
1116 return Some((qself, path));
1121 /// If the given expression is a path to a unit struct, returns that path.
1122 /// It is not a complete check, but just tries to reject most paths early
1123 /// if they are not unit structs.
1124 /// Type checking will take care of the full validation later.
1125 fn extract_unit_struct_path<'a>(
1128 ) -> Option<(&'a Option<AstP<QSelf>>, &'a Path)> {
1129 if let ExprKind::Path(qself, path) = &expr.kind {
1130 // Does the path resolve to something disallowed in a unit struct/variant pattern?
1131 if let Some(partial_res) = self.resolver.get_partial_res(expr.id) {
1132 if let Some(res) = partial_res.full_res() && !res.expected_in_unit_struct_pat() {
1136 return Some((qself, path));
1141 /// Convert the LHS of a destructuring assignment to a pattern.
1142 /// Each sub-assignment is recorded in `assignments`.
1143 fn destructure_assign(
1147 assignments: &mut Vec<hir::Stmt<'hir>>,
1148 ) -> &'hir hir::Pat<'hir> {
1149 self.arena.alloc(self.destructure_assign_mut(lhs, eq_sign_span, assignments))
1152 fn destructure_assign_mut(
1156 assignments: &mut Vec<hir::Stmt<'hir>>,
1157 ) -> hir::Pat<'hir> {
1159 // Underscore pattern.
1160 ExprKind::Underscore => {
1161 return self.pat_without_dbm(lhs.span, hir::PatKind::Wild);
1164 ExprKind::Array(elements) => {
1166 self.destructure_sequence(elements, "slice", eq_sign_span, assignments);
1167 let slice_pat = if let Some((i, span)) = rest {
1168 let (before, after) = pats.split_at(i);
1169 hir::PatKind::Slice(
1171 Some(self.arena.alloc(self.pat_without_dbm(span, hir::PatKind::Wild))),
1175 hir::PatKind::Slice(pats, None, &[])
1177 return self.pat_without_dbm(lhs.span, slice_pat);
1180 ExprKind::Call(callee, args) => {
1181 if let Some((qself, path)) = self.extract_tuple_struct_path(callee) {
1182 let (pats, rest) = self.destructure_sequence(
1184 "tuple struct or variant",
1188 let qpath = self.lower_qpath(
1192 ParamMode::Optional,
1193 &ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1195 // Destructure like a tuple struct.
1196 let tuple_struct_pat = hir::PatKind::TupleStruct(
1199 hir::DotDotPos::new(rest.map(|r| r.0)),
1201 return self.pat_without_dbm(lhs.span, tuple_struct_pat);
1204 // Unit structs and enum variants.
1205 ExprKind::Path(..) => {
1206 if let Some((qself, path)) = self.extract_unit_struct_path(lhs) {
1207 let qpath = self.lower_qpath(
1211 ParamMode::Optional,
1212 &ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1214 // Destructure like a unit struct.
1215 let unit_struct_pat = hir::PatKind::Path(qpath);
1216 return self.pat_without_dbm(lhs.span, unit_struct_pat);
1220 ExprKind::Struct(se) => {
1221 let field_pats = self.arena.alloc_from_iter(se.fields.iter().map(|f| {
1222 let pat = self.destructure_assign(&f.expr, eq_sign_span, assignments);
1224 hir_id: self.next_id(),
1225 ident: self.lower_ident(f.ident),
1227 is_shorthand: f.is_shorthand,
1228 span: self.lower_span(f.span),
1231 let qpath = self.lower_qpath(
1235 ParamMode::Optional,
1236 &ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1238 let fields_omitted = match &se.rest {
1239 StructRest::Base(e) => {
1240 self.tcx.sess.emit_err(FunctionalRecordUpdateDestructuringAssignemnt {
1245 StructRest::Rest(_) => true,
1246 StructRest::None => false,
1248 let struct_pat = hir::PatKind::Struct(qpath, field_pats, fields_omitted);
1249 return self.pat_without_dbm(lhs.span, struct_pat);
1252 ExprKind::Tup(elements) => {
1254 self.destructure_sequence(elements, "tuple", eq_sign_span, assignments);
1255 let tuple_pat = hir::PatKind::Tuple(pats, hir::DotDotPos::new(rest.map(|r| r.0)));
1256 return self.pat_without_dbm(lhs.span, tuple_pat);
1258 ExprKind::Paren(e) => {
1259 // We special-case `(..)` for consistency with patterns.
1260 if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
1261 let tuple_pat = hir::PatKind::Tuple(&[], hir::DotDotPos::new(Some(0)));
1262 return self.pat_without_dbm(lhs.span, tuple_pat);
1264 return self.destructure_assign_mut(e, eq_sign_span, assignments);
1269 // Treat all other cases as normal lvalue.
1270 let ident = Ident::new(sym::lhs, self.lower_span(lhs.span));
1271 let (pat, binding) = self.pat_ident_mut(lhs.span, ident);
1272 let ident = self.expr_ident(lhs.span, ident, binding);
1274 hir::ExprKind::Assign(self.lower_expr(lhs), ident, self.lower_span(eq_sign_span));
1275 let expr = self.expr(lhs.span, assign, AttrVec::new());
1276 assignments.push(self.stmt_expr(lhs.span, expr));
1280 /// Destructure a sequence of expressions occurring on the LHS of an assignment.
1281 /// Such a sequence occurs in a tuple (struct)/slice.
1282 /// Return a sequence of corresponding patterns, and the index and the span of `..` if it
1284 /// Each sub-assignment is recorded in `assignments`.
1285 fn destructure_sequence(
1287 elements: &[AstP<Expr>],
1290 assignments: &mut Vec<hir::Stmt<'hir>>,
1291 ) -> (&'hir [hir::Pat<'hir>], Option<(usize, Span)>) {
1292 let mut rest = None;
1294 self.arena.alloc_from_iter(elements.iter().enumerate().filter_map(|(i, e)| {
1295 // Check for `..` pattern.
1296 if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
1297 if let Some((_, prev_span)) = rest {
1298 self.ban_extra_rest_pat(e.span, prev_span, ctx);
1300 rest = Some((i, e.span));
1304 Some(self.destructure_assign_mut(e, eq_sign_span, assignments))
1310 /// Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`.
1311 fn lower_expr_range_closed(&mut self, span: Span, e1: &Expr, e2: &Expr) -> hir::ExprKind<'hir> {
1312 let e1 = self.lower_expr_mut(e1);
1313 let e2 = self.lower_expr_mut(e2);
1315 hir::QPath::LangItem(hir::LangItem::RangeInclusiveNew, self.lower_span(span), None);
1317 self.arena.alloc(self.expr(span, hir::ExprKind::Path(fn_path), AttrVec::new()));
1318 hir::ExprKind::Call(fn_expr, arena_vec![self; e1, e2])
1321 fn lower_expr_range(
1327 ) -> hir::ExprKind<'hir> {
1328 use rustc_ast::RangeLimits::*;
1330 let lang_item = match (e1, e2, lims) {
1331 (None, None, HalfOpen) => hir::LangItem::RangeFull,
1332 (Some(..), None, HalfOpen) => hir::LangItem::RangeFrom,
1333 (None, Some(..), HalfOpen) => hir::LangItem::RangeTo,
1334 (Some(..), Some(..), HalfOpen) => hir::LangItem::Range,
1335 (None, Some(..), Closed) => hir::LangItem::RangeToInclusive,
1336 (Some(..), Some(..), Closed) => unreachable!(),
1337 (start, None, Closed) => {
1338 self.tcx.sess.emit_err(InclusiveRangeWithNoEnd { span });
1340 Some(..) => hir::LangItem::RangeFrom,
1341 None => hir::LangItem::RangeFull,
1346 let fields = self.arena.alloc_from_iter(
1347 e1.iter().map(|e| (sym::start, e)).chain(e2.iter().map(|e| (sym::end, e))).map(
1349 let expr = self.lower_expr(&e);
1350 let ident = Ident::new(s, self.lower_span(e.span));
1351 self.expr_field(ident, expr, e.span)
1356 hir::ExprKind::Struct(
1357 self.arena.alloc(hir::QPath::LangItem(lang_item, self.lower_span(span), None)),
1363 fn lower_label(&self, opt_label: Option<Label>) -> Option<Label> {
1364 let label = opt_label?;
1365 Some(Label { ident: self.lower_ident(label.ident) })
1368 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
1369 let target_id = match destination {
1371 if let Some(loop_id) = self.resolver.get_label_res(id) {
1372 Ok(self.lower_node_id(loop_id))
1374 Err(hir::LoopIdError::UnresolvedLabel)
1379 .map(|id| Ok(self.lower_node_id(id)))
1380 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope)),
1382 let label = self.lower_label(destination.map(|(_, label)| label));
1383 hir::Destination { label, target_id }
1386 fn lower_jump_destination(&mut self, id: NodeId, opt_label: Option<Label>) -> hir::Destination {
1387 if self.is_in_loop_condition && opt_label.is_none() {
1390 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition),
1393 self.lower_loop_destination(opt_label.map(|label| (id, label)))
1397 fn with_catch_scope<T>(&mut self, catch_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1398 let old_scope = self.catch_scope.replace(catch_id);
1399 let result = f(self);
1400 self.catch_scope = old_scope;
1404 fn with_loop_scope<T>(&mut self, loop_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1405 // We're no longer in the base loop's condition; we're in another loop.
1406 let was_in_loop_condition = self.is_in_loop_condition;
1407 self.is_in_loop_condition = false;
1409 let old_scope = self.loop_scope.replace(loop_id);
1410 let result = f(self);
1411 self.loop_scope = old_scope;
1413 self.is_in_loop_condition = was_in_loop_condition;
1418 fn with_loop_condition_scope<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
1419 let was_in_loop_condition = self.is_in_loop_condition;
1420 self.is_in_loop_condition = true;
1422 let result = f(self);
1424 self.is_in_loop_condition = was_in_loop_condition;
1429 fn lower_expr_field(&mut self, f: &ExprField) -> hir::ExprField<'hir> {
1430 let hir_id = self.lower_node_id(f.id);
1431 self.lower_attrs(hir_id, &f.attrs);
1434 ident: self.lower_ident(f.ident),
1435 expr: self.lower_expr(&f.expr),
1436 span: self.lower_span(f.span),
1437 is_shorthand: f.is_shorthand,
1441 fn lower_expr_yield(&mut self, span: Span, opt_expr: Option<&Expr>) -> hir::ExprKind<'hir> {
1442 match self.generator_kind {
1443 Some(hir::GeneratorKind::Gen) => {}
1444 Some(hir::GeneratorKind::Async(_)) => {
1445 self.tcx.sess.emit_err(AsyncGeneratorsNotSupported { span });
1447 None => self.generator_kind = Some(hir::GeneratorKind::Gen),
1451 opt_expr.as_ref().map(|x| self.lower_expr(x)).unwrap_or_else(|| self.expr_unit(span));
1453 hir::ExprKind::Yield(expr, hir::YieldSource::Yield)
1456 /// Desugar `ExprForLoop` from: `[opt_ident]: for <pat> in <head> <body>` into:
1457 /// ```ignore (pseudo-rust)
1459 /// let result = match IntoIterator::into_iter(<head>) {
1461 /// [opt_ident]: loop {
1462 /// match Iterator::next(&mut iter) {
1464 /// Some(<pat>) => <body>,
1478 opt_label: Option<Label>,
1479 ) -> hir::Expr<'hir> {
1480 let head = self.lower_expr_mut(head);
1481 let pat = self.lower_pat(pat);
1483 self.mark_span_with_reason(DesugaringKind::ForLoop, self.lower_span(e.span), None);
1484 let head_span = self.mark_span_with_reason(DesugaringKind::ForLoop, head.span, None);
1485 let pat_span = self.mark_span_with_reason(DesugaringKind::ForLoop, pat.span, None);
1490 self.with_loop_scope(e.id, |this| this.expr_break_alloc(for_span, AttrVec::new()));
1491 let pat = self.pat_none(for_span);
1492 self.arm(pat, break_expr)
1495 // Some(<pat>) => <body>,
1497 let some_pat = self.pat_some(pat_span, pat);
1498 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
1499 let body_expr = self.arena.alloc(self.expr_block(body_block, AttrVec::new()));
1500 self.arm(some_pat, body_expr)
1504 let iter = Ident::with_dummy_span(sym::iter);
1505 let (iter_pat, iter_pat_nid) =
1506 self.pat_ident_binding_mode(head_span, iter, hir::BindingAnnotation::MUT);
1508 // `match Iterator::next(&mut iter) { ... }`
1510 let iter = self.expr_ident(head_span, iter, iter_pat_nid);
1511 let ref_mut_iter = self.expr_mut_addr_of(head_span, iter);
1512 let next_expr = self.expr_call_lang_item_fn(
1514 hir::LangItem::IteratorNext,
1515 arena_vec![self; ref_mut_iter],
1518 let arms = arena_vec![self; none_arm, some_arm];
1520 self.expr_match(head_span, next_expr, arms, hir::MatchSource::ForLoopDesugar)
1522 let match_stmt = self.stmt_expr(for_span, match_expr);
1524 let loop_block = self.block_all(for_span, arena_vec![self; match_stmt], None);
1526 // `[opt_ident]: loop { ... }`
1527 let kind = hir::ExprKind::Loop(
1529 self.lower_label(opt_label),
1530 hir::LoopSource::ForLoop,
1531 self.lower_span(for_span.with_hi(head.span.hi())),
1534 self.arena.alloc(hir::Expr { hir_id: self.lower_node_id(e.id), kind, span: for_span });
1536 // `mut iter => { ... }`
1537 let iter_arm = self.arm(iter_pat, loop_expr);
1539 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
1540 let into_iter_expr = {
1541 self.expr_call_lang_item_fn(
1543 hir::LangItem::IntoIterIntoIter,
1544 arena_vec![self; head],
1549 let match_expr = self.arena.alloc(self.expr_match(
1552 arena_vec![self; iter_arm],
1553 hir::MatchSource::ForLoopDesugar,
1556 // This is effectively `{ let _result = ...; _result }`.
1557 // The construct was introduced in #21984 and is necessary to make sure that
1558 // temporaries in the `head` expression are dropped and do not leak to the
1559 // surrounding scope of the `match` since the `match` is not a terminating scope.
1561 // Also, add the attributes to the outer returned expr node.
1562 self.expr_drop_temps_mut(for_span, match_expr, e.attrs.clone())
1565 /// Desugar `ExprKind::Try` from: `<expr>?` into:
1566 /// ```ignore (pseudo-rust)
1567 /// match Try::branch(<expr>) {
1568 /// ControlFlow::Continue(val) => #[allow(unreachable_code)] val,,
1569 /// ControlFlow::Break(residual) =>
1570 /// #[allow(unreachable_code)]
1571 /// // If there is an enclosing `try {...}`:
1572 /// break 'catch_target Try::from_residual(residual),
1574 /// return Try::from_residual(residual),
1577 fn lower_expr_try(&mut self, span: Span, sub_expr: &Expr) -> hir::ExprKind<'hir> {
1578 let unstable_span = self.mark_span_with_reason(
1579 DesugaringKind::QuestionMark,
1581 self.allow_try_trait.clone(),
1583 let try_span = self.tcx.sess.source_map().end_point(span);
1584 let try_span = self.mark_span_with_reason(
1585 DesugaringKind::QuestionMark,
1587 self.allow_try_trait.clone(),
1590 // `Try::branch(<expr>)`
1593 let sub_expr = self.lower_expr_mut(sub_expr);
1595 self.expr_call_lang_item_fn(
1597 hir::LangItem::TryTraitBranch,
1598 arena_vec![self; sub_expr],
1603 // `#[allow(unreachable_code)]`
1605 // `allow(unreachable_code)`
1607 let allow_ident = Ident::new(sym::allow, self.lower_span(span));
1608 let uc_ident = Ident::new(sym::unreachable_code, self.lower_span(span));
1609 let uc_nested = attr::mk_nested_word_item(uc_ident);
1610 attr::mk_list_item(allow_ident, vec![uc_nested])
1612 attr::mk_attr_outer(&self.tcx.sess.parse_sess.attr_id_generator, allow)
1614 let attrs: AttrVec = thin_vec![attr];
1616 // `ControlFlow::Continue(val) => #[allow(unreachable_code)] val,`
1617 let continue_arm = {
1618 let val_ident = Ident::with_dummy_span(sym::val);
1619 let (val_pat, val_pat_nid) = self.pat_ident(span, val_ident);
1620 let val_expr = self.arena.alloc(self.expr_ident_with_attrs(
1626 let continue_pat = self.pat_cf_continue(unstable_span, val_pat);
1627 self.arm(continue_pat, val_expr)
1630 // `ControlFlow::Break(residual) =>
1631 // #[allow(unreachable_code)]
1632 // return Try::from_residual(residual),`
1634 let residual_ident = Ident::with_dummy_span(sym::residual);
1635 let (residual_local, residual_local_nid) = self.pat_ident(try_span, residual_ident);
1636 let residual_expr = self.expr_ident_mut(try_span, residual_ident, residual_local_nid);
1637 let from_residual_expr = self.wrap_in_try_constructor(
1638 hir::LangItem::TryTraitFromResidual,
1640 self.arena.alloc(residual_expr),
1643 let ret_expr = if let Some(catch_node) = self.catch_scope {
1644 let target_id = Ok(self.lower_node_id(catch_node));
1645 self.arena.alloc(self.expr(
1647 hir::ExprKind::Break(
1648 hir::Destination { label: None, target_id },
1649 Some(from_residual_expr),
1654 self.arena.alloc(self.expr(
1656 hir::ExprKind::Ret(Some(from_residual_expr)),
1661 let break_pat = self.pat_cf_break(try_span, residual_local);
1662 self.arm(break_pat, ret_expr)
1665 hir::ExprKind::Match(
1667 arena_vec![self; break_arm, continue_arm],
1668 hir::MatchSource::TryDesugar,
1672 /// Desugar `ExprKind::Yeet` from: `do yeet <expr>` into:
1673 /// ```ignore(illustrative)
1674 /// // If there is an enclosing `try {...}`:
1675 /// break 'catch_target FromResidual::from_residual(Yeet(residual));
1677 /// return FromResidual::from_residual(Yeet(residual));
1679 /// But to simplify this, there's a `from_yeet` lang item function which
1680 /// handles the combined `FromResidual::from_residual(Yeet(residual))`.
1681 fn lower_expr_yeet(&mut self, span: Span, sub_expr: Option<&Expr>) -> hir::ExprKind<'hir> {
1682 // The expression (if present) or `()` otherwise.
1683 let (yeeted_span, yeeted_expr) = if let Some(sub_expr) = sub_expr {
1684 (sub_expr.span, self.lower_expr(sub_expr))
1686 (self.mark_span_with_reason(DesugaringKind::YeetExpr, span, None), self.expr_unit(span))
1689 let unstable_span = self.mark_span_with_reason(
1690 DesugaringKind::YeetExpr,
1692 self.allow_try_trait.clone(),
1695 let from_yeet_expr = self.wrap_in_try_constructor(
1696 hir::LangItem::TryTraitFromYeet,
1702 if let Some(catch_node) = self.catch_scope {
1703 let target_id = Ok(self.lower_node_id(catch_node));
1704 hir::ExprKind::Break(hir::Destination { label: None, target_id }, Some(from_yeet_expr))
1706 hir::ExprKind::Ret(Some(from_yeet_expr))
1710 // =========================================================================
1711 // Helper methods for building HIR.
1712 // =========================================================================
1714 /// Wrap the given `expr` in a terminating scope using `hir::ExprKind::DropTemps`.
1716 /// In terms of drop order, it has the same effect as wrapping `expr` in
1717 /// `{ let _t = $expr; _t }` but should provide better compile-time performance.
1719 /// The drop order can be important in e.g. `if expr { .. }`.
1720 pub(super) fn expr_drop_temps(
1723 expr: &'hir hir::Expr<'hir>,
1725 ) -> &'hir hir::Expr<'hir> {
1726 self.arena.alloc(self.expr_drop_temps_mut(span, expr, attrs))
1729 pub(super) fn expr_drop_temps_mut(
1732 expr: &'hir hir::Expr<'hir>,
1734 ) -> hir::Expr<'hir> {
1735 self.expr(span, hir::ExprKind::DropTemps(expr), attrs)
1741 arg: &'hir hir::Expr<'hir>,
1742 arms: &'hir [hir::Arm<'hir>],
1743 source: hir::MatchSource,
1744 ) -> hir::Expr<'hir> {
1745 self.expr(span, hir::ExprKind::Match(arg, arms, source), AttrVec::new())
1748 fn expr_break(&mut self, span: Span, attrs: AttrVec) -> hir::Expr<'hir> {
1749 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
1750 self.expr(span, expr_break, attrs)
1753 fn expr_break_alloc(&mut self, span: Span, attrs: AttrVec) -> &'hir hir::Expr<'hir> {
1754 let expr_break = self.expr_break(span, attrs);
1755 self.arena.alloc(expr_break)
1758 fn expr_mut_addr_of(&mut self, span: Span, e: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
1761 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Mut, e),
1766 fn expr_unit(&mut self, sp: Span) -> &'hir hir::Expr<'hir> {
1767 self.arena.alloc(self.expr(sp, hir::ExprKind::Tup(&[]), AttrVec::new()))
1773 e: &'hir hir::Expr<'hir>,
1774 args: &'hir [hir::Expr<'hir>],
1775 ) -> hir::Expr<'hir> {
1776 self.expr(span, hir::ExprKind::Call(e, args), AttrVec::new())
1782 e: &'hir hir::Expr<'hir>,
1783 args: &'hir [hir::Expr<'hir>],
1784 ) -> &'hir hir::Expr<'hir> {
1785 self.arena.alloc(self.expr_call_mut(span, e, args))
1788 fn expr_call_lang_item_fn_mut(
1791 lang_item: hir::LangItem,
1792 args: &'hir [hir::Expr<'hir>],
1793 hir_id: Option<hir::HirId>,
1794 ) -> hir::Expr<'hir> {
1796 self.arena.alloc(self.expr_lang_item_path(span, lang_item, AttrVec::new(), hir_id));
1797 self.expr_call_mut(span, path, args)
1800 fn expr_call_lang_item_fn(
1803 lang_item: hir::LangItem,
1804 args: &'hir [hir::Expr<'hir>],
1805 hir_id: Option<hir::HirId>,
1806 ) -> &'hir hir::Expr<'hir> {
1807 self.arena.alloc(self.expr_call_lang_item_fn_mut(span, lang_item, args, hir_id))
1810 fn expr_lang_item_path(
1813 lang_item: hir::LangItem,
1815 hir_id: Option<hir::HirId>,
1816 ) -> hir::Expr<'hir> {
1819 hir::ExprKind::Path(hir::QPath::LangItem(lang_item, self.lower_span(span), hir_id)),
1824 pub(super) fn expr_ident(
1828 binding: hir::HirId,
1829 ) -> &'hir hir::Expr<'hir> {
1830 self.arena.alloc(self.expr_ident_mut(sp, ident, binding))
1833 pub(super) fn expr_ident_mut(
1837 binding: hir::HirId,
1838 ) -> hir::Expr<'hir> {
1839 self.expr_ident_with_attrs(sp, ident, binding, AttrVec::new())
1842 fn expr_ident_with_attrs(
1846 binding: hir::HirId,
1848 ) -> hir::Expr<'hir> {
1849 let hir_id = self.next_id();
1850 let res = Res::Local(binding);
1851 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
1853 self.arena.alloc(hir::Path {
1854 span: self.lower_span(span),
1856 segments: arena_vec![self; hir::PathSegment::new(ident, hir_id, res)],
1860 self.expr(span, expr_path, attrs)
1863 fn expr_unsafe(&mut self, expr: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
1864 let hir_id = self.next_id();
1865 let span = expr.span;
1868 hir::ExprKind::Block(
1869 self.arena.alloc(hir::Block {
1873 rules: hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::CompilerGenerated),
1874 span: self.lower_span(span),
1875 targeted_by_break: false,
1883 fn expr_block_empty(&mut self, span: Span) -> &'hir hir::Expr<'hir> {
1884 let blk = self.block_all(span, &[], None);
1885 let expr = self.expr_block(blk, AttrVec::new());
1886 self.arena.alloc(expr)
1889 pub(super) fn expr_block(
1891 b: &'hir hir::Block<'hir>,
1893 ) -> hir::Expr<'hir> {
1894 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
1900 kind: hir::ExprKind<'hir>,
1902 ) -> hir::Expr<'hir> {
1903 let hir_id = self.next_id();
1904 self.lower_attrs(hir_id, &attrs);
1905 hir::Expr { hir_id, kind, span: self.lower_span(span) }
1911 expr: &'hir hir::Expr<'hir>,
1913 ) -> hir::ExprField<'hir> {
1915 hir_id: self.next_id(),
1917 span: self.lower_span(span),
1919 is_shorthand: false,
1923 fn arm(&mut self, pat: &'hir hir::Pat<'hir>, expr: &'hir hir::Expr<'hir>) -> hir::Arm<'hir> {
1925 hir_id: self.next_id(),
1928 span: self.lower_span(expr.span),