1 use super::ResolverAstLoweringExt;
2 use super::{ImplTraitContext, LoweringContext, ParamMode, ParenthesizedGenericArgs};
3 use crate::{FnDeclKind, ImplTraitPosition};
6 use rustc_ast::ptr::P as AstP;
8 use rustc_data_structures::stack::ensure_sufficient_stack;
9 use rustc_data_structures::thin_vec::ThinVec;
10 use rustc_errors::struct_span_err;
12 use rustc_hir::def::Res;
13 use rustc_hir::definitions::DefPathData;
14 use rustc_span::source_map::{respan, DesugaringKind, Span, Spanned};
15 use rustc_span::symbol::{sym, Ident};
16 use rustc_span::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_array_length(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 e.attrs.get(0).map_or(false, |a| a.has_name(sym::rustc_box)) {
44 if let [inner] = &args[..] && e.attrs.len() == 1 {
45 let kind = hir::ExprKind::Box(self.lower_expr(&inner));
46 let hir_id = self.lower_node_id(e.id);
47 return hir::Expr { hir_id, kind, span: self.lower_span(e.span) };
52 "#[rustc_box] requires precisely one argument \
53 and no other attributes are allowed",
58 } else if let Some(legacy_args) = self.resolver.legacy_const_generic_args(f) {
59 self.lower_legacy_const_generics((**f).clone(), args.clone(), &legacy_args)
61 let f = self.lower_expr(f);
62 hir::ExprKind::Call(f, self.lower_exprs(args))
65 ExprKind::MethodCall(ref seg, ref args, span) => {
66 let hir_seg = self.arena.alloc(self.lower_path_segment(
70 ParenthesizedGenericArgs::Err,
71 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
73 let args = self.lower_exprs(args);
74 hir::ExprKind::MethodCall(hir_seg, args, self.lower_span(span))
76 ExprKind::Binary(binop, ref lhs, ref rhs) => {
77 let binop = self.lower_binop(binop);
78 let lhs = self.lower_expr(lhs);
79 let rhs = self.lower_expr(rhs);
80 hir::ExprKind::Binary(binop, lhs, rhs)
82 ExprKind::Unary(op, ref ohs) => {
83 let op = self.lower_unop(op);
84 let ohs = self.lower_expr(ohs);
85 hir::ExprKind::Unary(op, ohs)
87 ExprKind::Lit(ref l) => {
88 hir::ExprKind::Lit(respan(self.lower_span(l.span), l.kind.clone()))
90 ExprKind::Cast(ref expr, ref ty) => {
91 let expr = self.lower_expr(expr);
93 self.lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type));
94 hir::ExprKind::Cast(expr, ty)
96 ExprKind::Type(ref expr, ref ty) => {
97 let expr = self.lower_expr(expr);
99 self.lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type));
100 hir::ExprKind::Type(expr, ty)
102 ExprKind::AddrOf(k, m, ref ohs) => {
103 let ohs = self.lower_expr(ohs);
104 hir::ExprKind::AddrOf(k, m, ohs)
106 ExprKind::Let(ref pat, ref scrutinee, span) => {
107 hir::ExprKind::Let(self.arena.alloc(hir::Let {
108 hir_id: self.next_id(),
109 span: self.lower_span(span),
110 pat: self.lower_pat(pat),
112 init: self.lower_expr(scrutinee),
115 ExprKind::If(ref cond, ref then, ref else_opt) => {
116 self.lower_expr_if(cond, then, else_opt.as_deref())
118 ExprKind::While(ref cond, ref body, opt_label) => {
119 self.with_loop_scope(e.id, |this| {
121 this.mark_span_with_reason(DesugaringKind::WhileLoop, e.span, None);
122 this.lower_expr_while_in_loop_scope(span, cond, body, opt_label)
125 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
127 this.lower_block(body, false),
128 this.lower_label(opt_label),
129 hir::LoopSource::Loop,
133 ExprKind::TryBlock(ref body) => self.lower_expr_try_block(body),
134 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
135 self.lower_expr(expr),
136 self.arena.alloc_from_iter(arms.iter().map(|x| self.lower_arm(x))),
137 hir::MatchSource::Normal,
139 ExprKind::Async(capture_clause, closure_node_id, ref block) => self
145 hir::AsyncGeneratorKind::Block,
146 |this| this.with_new_scopes(|this| this.lower_block_expr(block)),
148 ExprKind::Await(ref expr) => {
149 let span = if expr.span.hi() < e.span.hi() {
150 expr.span.shrink_to_hi().with_hi(e.span.hi())
152 // this is a recovered `await expr`
155 self.lower_expr_await(span, expr)
166 if let Async::Yes { closure_id, .. } = asyncness {
167 self.lower_expr_async_closure(
177 self.lower_expr_closure(
188 ExprKind::Block(ref blk, opt_label) => {
189 let opt_label = self.lower_label(opt_label);
190 hir::ExprKind::Block(self.lower_block(blk, opt_label.is_some()), opt_label)
192 ExprKind::Assign(ref el, ref er, span) => {
193 self.lower_expr_assign(el, er, span, e.span)
195 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
196 self.lower_binop(op),
200 ExprKind::Field(ref el, ident) => {
201 hir::ExprKind::Field(self.lower_expr(el), self.lower_ident(ident))
203 ExprKind::Index(ref el, ref er) => {
204 hir::ExprKind::Index(self.lower_expr(el), self.lower_expr(er))
206 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
207 self.lower_expr_range_closed(e.span, e1, e2)
209 ExprKind::Range(ref e1, ref e2, lims) => {
210 self.lower_expr_range(e.span, e1.as_deref(), e2.as_deref(), lims)
212 ExprKind::Underscore => {
214 .sess.struct_span_err(
216 "in expressions, `_` can only be used on the left-hand side of an assignment",
218 .span_label(e.span, "`_` not allowed here")
222 ExprKind::Path(ref qself, ref path) => {
223 let qpath = self.lower_qpath(
228 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
230 hir::ExprKind::Path(qpath)
232 ExprKind::Break(opt_label, ref opt_expr) => {
233 let opt_expr = opt_expr.as_ref().map(|x| self.lower_expr(x));
234 hir::ExprKind::Break(self.lower_jump_destination(e.id, opt_label), opt_expr)
236 ExprKind::Continue(opt_label) => {
237 hir::ExprKind::Continue(self.lower_jump_destination(e.id, opt_label))
239 ExprKind::Ret(ref e) => {
240 let e = e.as_ref().map(|x| self.lower_expr(x));
241 hir::ExprKind::Ret(e)
243 ExprKind::Yeet(ref sub_expr) => self.lower_expr_yeet(e.span, sub_expr.as_deref()),
244 ExprKind::InlineAsm(ref asm) => {
245 hir::ExprKind::InlineAsm(self.lower_inline_asm(e.span, asm))
247 ExprKind::Struct(ref se) => {
248 let rest = match &se.rest {
249 StructRest::Base(e) => Some(self.lower_expr(e)),
250 StructRest::Rest(sp) => {
253 .struct_span_err(*sp, "base expression required after `..`")
254 .span_label(*sp, "add a base expression here")
256 Some(&*self.arena.alloc(self.expr_err(*sp)))
258 StructRest::None => None,
260 hir::ExprKind::Struct(
261 self.arena.alloc(self.lower_qpath(
266 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
269 .alloc_from_iter(se.fields.iter().map(|x| self.lower_expr_field(x))),
273 ExprKind::Yield(ref opt_expr) => self.lower_expr_yield(e.span, opt_expr.as_deref()),
274 ExprKind::Err => hir::ExprKind::Err,
275 ExprKind::Try(ref sub_expr) => self.lower_expr_try(e.span, sub_expr),
276 ExprKind::Paren(ref ex) => {
277 let mut ex = self.lower_expr_mut(ex);
278 // Include parens in span, but only if it is a super-span.
279 if e.span.contains(ex.span) {
280 ex.span = self.lower_span(e.span);
282 // Merge attributes into the inner expression.
283 if !e.attrs.is_empty() {
285 self.attrs.get(&ex.hir_id.local_id).map(|la| *la).unwrap_or(&[]);
288 &*self.arena.alloc_from_iter(
291 .map(|a| self.lower_attr(a))
292 .chain(old_attrs.iter().cloned()),
299 // Desugar `ExprForLoop`
300 // from: `[opt_ident]: for <pat> in <head> <body>`
301 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
302 return self.lower_expr_for(e, pat, head, body, opt_label);
304 ExprKind::MacCall(_) => panic!("{:?} shouldn't exist here", e.span),
307 let hir_id = self.lower_node_id(e.id);
308 self.lower_attrs(hir_id, &e.attrs);
309 hir::Expr { hir_id, kind, span: self.lower_span(e.span) }
313 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
315 UnOp::Deref => hir::UnOp::Deref,
316 UnOp::Not => hir::UnOp::Not,
317 UnOp::Neg => hir::UnOp::Neg,
321 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
324 BinOpKind::Add => hir::BinOpKind::Add,
325 BinOpKind::Sub => hir::BinOpKind::Sub,
326 BinOpKind::Mul => hir::BinOpKind::Mul,
327 BinOpKind::Div => hir::BinOpKind::Div,
328 BinOpKind::Rem => hir::BinOpKind::Rem,
329 BinOpKind::And => hir::BinOpKind::And,
330 BinOpKind::Or => hir::BinOpKind::Or,
331 BinOpKind::BitXor => hir::BinOpKind::BitXor,
332 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
333 BinOpKind::BitOr => hir::BinOpKind::BitOr,
334 BinOpKind::Shl => hir::BinOpKind::Shl,
335 BinOpKind::Shr => hir::BinOpKind::Shr,
336 BinOpKind::Eq => hir::BinOpKind::Eq,
337 BinOpKind::Lt => hir::BinOpKind::Lt,
338 BinOpKind::Le => hir::BinOpKind::Le,
339 BinOpKind::Ne => hir::BinOpKind::Ne,
340 BinOpKind::Ge => hir::BinOpKind::Ge,
341 BinOpKind::Gt => hir::BinOpKind::Gt,
343 span: self.lower_span(b.span),
347 fn lower_legacy_const_generics(
350 args: Vec<AstP<Expr>>,
351 legacy_args_idx: &[usize],
352 ) -> hir::ExprKind<'hir> {
353 let ExprKind::Path(None, ref mut path) = f.kind else {
357 // Split the arguments into const generics and normal arguments
358 let mut real_args = vec![];
359 let mut generic_args = vec![];
360 for (idx, arg) in args.into_iter().enumerate() {
361 if legacy_args_idx.contains(&idx) {
362 let parent_def_id = self.current_hir_id_owner;
363 let node_id = self.next_node_id();
365 // Add a definition for the in-band const def.
366 self.create_def(parent_def_id, node_id, DefPathData::AnonConst);
368 let anon_const = AnonConst { id: node_id, value: arg };
369 generic_args.push(AngleBracketedArg::Arg(GenericArg::Const(anon_const)));
375 // Add generic args to the last element of the path.
376 let last_segment = path.segments.last_mut().unwrap();
377 assert!(last_segment.args.is_none());
378 last_segment.args = Some(AstP(GenericArgs::AngleBracketed(AngleBracketedArgs {
383 // Now lower everything as normal.
384 let f = self.lower_expr(&f);
385 hir::ExprKind::Call(f, self.lower_exprs(&real_args))
392 else_opt: Option<&Expr>,
393 ) -> hir::ExprKind<'hir> {
394 let lowered_cond = self.lower_expr(cond);
395 let new_cond = self.manage_let_cond(lowered_cond);
396 let then_expr = self.lower_block_expr(then);
397 if let Some(rslt) = else_opt {
398 hir::ExprKind::If(new_cond, self.arena.alloc(then_expr), Some(self.lower_expr(rslt)))
400 hir::ExprKind::If(new_cond, self.arena.alloc(then_expr), None)
404 // If `cond` kind is `let`, returns `let`. Otherwise, wraps and returns `cond`
405 // in a temporary block.
406 fn manage_let_cond(&mut self, cond: &'hir hir::Expr<'hir>) -> &'hir hir::Expr<'hir> {
407 fn has_let_expr<'hir>(expr: &'hir hir::Expr<'hir>) -> bool {
409 hir::ExprKind::Binary(_, lhs, rhs) => has_let_expr(lhs) || has_let_expr(rhs),
410 hir::ExprKind::Let(..) => true,
414 if has_let_expr(cond) {
417 let reason = DesugaringKind::CondTemporary;
418 let span_block = self.mark_span_with_reason(reason, cond.span, None);
419 self.expr_drop_temps(span_block, cond, AttrVec::new())
423 // We desugar: `'label: while $cond $body` into:
427 // if { let _t = $cond; _t } {
436 // Wrap in a construct equivalent to `{ let _t = $cond; _t }`
437 // to preserve drop semantics since `while $cond { ... }` does not
438 // let temporaries live outside of `cond`.
439 fn lower_expr_while_in_loop_scope(
444 opt_label: Option<Label>,
445 ) -> hir::ExprKind<'hir> {
446 let lowered_cond = self.with_loop_condition_scope(|t| t.lower_expr(cond));
447 let new_cond = self.manage_let_cond(lowered_cond);
448 let then = self.lower_block_expr(body);
449 let expr_break = self.expr_break(span, ThinVec::new());
450 let stmt_break = self.stmt_expr(span, expr_break);
451 let else_blk = self.block_all(span, arena_vec![self; stmt_break], None);
452 let else_expr = self.arena.alloc(self.expr_block(else_blk, ThinVec::new()));
453 let if_kind = hir::ExprKind::If(new_cond, self.arena.alloc(then), Some(else_expr));
454 let if_expr = self.expr(span, if_kind, ThinVec::new());
455 let block = self.block_expr(self.arena.alloc(if_expr));
456 let span = self.lower_span(span.with_hi(cond.span.hi()));
457 let opt_label = self.lower_label(opt_label);
458 hir::ExprKind::Loop(block, opt_label, hir::LoopSource::While, span)
461 /// Desugar `try { <stmts>; <expr> }` into `{ <stmts>; ::std::ops::Try::from_output(<expr>) }`,
462 /// `try { <stmts>; }` into `{ <stmts>; ::std::ops::Try::from_output(()) }`
463 /// and save the block id to use it as a break target for desugaring of the `?` operator.
464 fn lower_expr_try_block(&mut self, body: &Block) -> hir::ExprKind<'hir> {
465 self.with_catch_scope(body.id, |this| {
466 let mut block = this.lower_block_noalloc(body, true);
468 // Final expression of the block (if present) or `()` with span at the end of block
469 let (try_span, tail_expr) = if let Some(expr) = block.expr.take() {
471 this.mark_span_with_reason(
472 DesugaringKind::TryBlock,
474 this.allow_try_trait.clone(),
479 let try_span = this.mark_span_with_reason(
480 DesugaringKind::TryBlock,
481 this.tcx.sess.source_map().end_point(body.span),
482 this.allow_try_trait.clone(),
485 (try_span, this.expr_unit(try_span))
488 let ok_wrapped_span =
489 this.mark_span_with_reason(DesugaringKind::TryBlock, tail_expr.span, None);
491 // `::std::ops::Try::from_output($tail_expr)`
492 block.expr = Some(this.wrap_in_try_constructor(
493 hir::LangItem::TryTraitFromOutput,
499 hir::ExprKind::Block(this.arena.alloc(block), None)
503 fn wrap_in_try_constructor(
505 lang_item: hir::LangItem,
507 expr: &'hir hir::Expr<'hir>,
509 ) -> &'hir hir::Expr<'hir> {
510 let constructor = self.arena.alloc(self.expr_lang_item_path(
516 self.expr_call(overall_span, constructor, std::slice::from_ref(expr))
519 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm<'hir> {
520 let pat = self.lower_pat(&arm.pat);
521 let guard = arm.guard.as_ref().map(|cond| {
522 if let ExprKind::Let(ref pat, ref scrutinee, span) = cond.kind {
523 hir::Guard::IfLet(self.arena.alloc(hir::Let {
524 hir_id: self.next_id(),
525 span: self.lower_span(span),
526 pat: self.lower_pat(pat),
528 init: self.lower_expr(scrutinee),
531 hir::Guard::If(self.lower_expr(cond))
534 let hir_id = self.next_id();
535 self.lower_attrs(hir_id, &arm.attrs);
540 body: self.lower_expr(&arm.body),
541 span: self.lower_span(arm.span),
545 /// Lower an `async` construct to a generator that is then wrapped so it implements `Future`.
550 /// std::future::from_generator(static move? |_task_context| -> <ret_ty> {
554 pub(super) fn make_async_expr(
556 capture_clause: CaptureBy,
557 closure_node_id: NodeId,
558 ret_ty: Option<AstP<Ty>>,
560 async_gen_kind: hir::AsyncGeneratorKind,
561 body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
562 ) -> hir::ExprKind<'hir> {
563 let output = match ret_ty {
564 Some(ty) => hir::FnRetTy::Return(
565 self.lower_ty(&ty, ImplTraitContext::Disallowed(ImplTraitPosition::AsyncBlock)),
567 None => hir::FnRetTy::DefaultReturn(self.lower_span(span)),
570 // Resume argument type. We let the compiler infer this to simplify the lowering. It is
571 // fully constrained by `future::from_generator`.
572 let input_ty = hir::Ty {
573 hir_id: self.next_id(),
574 kind: hir::TyKind::Infer,
575 span: self.lower_span(span),
578 // The closure/generator `FnDecl` takes a single (resume) argument of type `input_ty`.
579 let fn_decl = self.arena.alloc(hir::FnDecl {
580 inputs: arena_vec![self; input_ty],
583 implicit_self: hir::ImplicitSelfKind::None,
586 // Lower the argument pattern/ident. The ident is used again in the `.await` lowering.
587 let (pat, task_context_hid) = self.pat_ident_binding_mode(
589 Ident::with_dummy_span(sym::_task_context),
590 hir::BindingAnnotation::Mutable,
592 let param = hir::Param {
593 hir_id: self.next_id(),
595 ty_span: self.lower_span(span),
596 span: self.lower_span(span),
598 let params = arena_vec![self; param];
600 let body = self.lower_body(move |this| {
601 this.generator_kind = Some(hir::GeneratorKind::Async(async_gen_kind));
603 let old_ctx = this.task_context;
604 this.task_context = Some(task_context_hid);
605 let res = body(this);
606 this.task_context = old_ctx;
610 // `static |_task_context| -> <ret_ty> { body }`:
611 let generator_kind = hir::ExprKind::Closure {
612 binder: &hir::ClosureBinder::Default,
614 bound_generic_params: &[],
617 fn_decl_span: self.lower_span(span),
618 movability: Some(hir::Movability::Static),
620 let generator = hir::Expr {
621 hir_id: self.lower_node_id(closure_node_id),
622 kind: generator_kind,
623 span: self.lower_span(span),
626 // `future::from_generator`:
628 self.mark_span_with_reason(DesugaringKind::Async, span, self.allow_gen_future.clone());
629 let gen_future = self.expr_lang_item_path(
631 hir::LangItem::FromGenerator,
636 // `future::from_generator(generator)`:
637 hir::ExprKind::Call(self.arena.alloc(gen_future), arena_vec![self; generator])
640 /// Desugar `<expr>.await` into:
641 /// ```ignore (pseudo-rust)
642 /// match ::std::future::IntoFuture::into_future(<expr>) {
643 /// mut __awaitee => loop {
644 /// match unsafe { ::std::future::Future::poll(
645 /// <::std::pin::Pin>::new_unchecked(&mut __awaitee),
646 /// ::std::future::get_context(task_context),
648 /// ::std::task::Poll::Ready(result) => break result,
649 /// ::std::task::Poll::Pending => {}
651 /// task_context = yield ();
655 fn lower_expr_await(&mut self, dot_await_span: Span, expr: &Expr) -> hir::ExprKind<'hir> {
656 let full_span = expr.span.to(dot_await_span);
657 match self.generator_kind {
658 Some(hir::GeneratorKind::Async(_)) => {}
659 Some(hir::GeneratorKind::Gen) | None => {
660 let mut err = struct_span_err!(
664 "`await` is only allowed inside `async` functions and blocks"
666 err.span_label(dot_await_span, "only allowed inside `async` functions and blocks");
667 if let Some(item_sp) = self.current_item {
668 err.span_label(item_sp, "this is not `async`");
673 let span = self.mark_span_with_reason(DesugaringKind::Await, dot_await_span, None);
674 let gen_future_span = self.mark_span_with_reason(
675 DesugaringKind::Await,
677 self.allow_gen_future.clone(),
679 let expr = self.lower_expr_mut(expr);
680 let expr_hir_id = expr.hir_id;
682 // Note that the name of this binding must not be changed to something else because
683 // debuggers and debugger extensions expect it to be called `__awaitee`. They use
684 // this name to identify what is being awaited by a suspended async functions.
685 let awaitee_ident = Ident::with_dummy_span(sym::__awaitee);
686 let (awaitee_pat, awaitee_pat_hid) =
687 self.pat_ident_binding_mode(span, awaitee_ident, hir::BindingAnnotation::Mutable);
689 let task_context_ident = Ident::with_dummy_span(sym::_task_context);
692 // ::std::future::Future::poll(
693 // ::std::pin::Pin::new_unchecked(&mut __awaitee),
694 // ::std::future::get_context(task_context),
698 let awaitee = self.expr_ident(span, awaitee_ident, awaitee_pat_hid);
699 let ref_mut_awaitee = self.expr_mut_addr_of(span, awaitee);
700 let task_context = if let Some(task_context_hid) = self.task_context {
701 self.expr_ident_mut(span, task_context_ident, task_context_hid)
703 // Use of `await` outside of an async context, we cannot use `task_context` here.
706 let new_unchecked = self.expr_call_lang_item_fn_mut(
708 hir::LangItem::PinNewUnchecked,
709 arena_vec![self; ref_mut_awaitee],
712 let get_context = self.expr_call_lang_item_fn_mut(
714 hir::LangItem::GetContext,
715 arena_vec![self; task_context],
718 let call = self.expr_call_lang_item_fn(
720 hir::LangItem::FuturePoll,
721 arena_vec![self; new_unchecked, get_context],
724 self.arena.alloc(self.expr_unsafe(call))
727 // `::std::task::Poll::Ready(result) => break result`
728 let loop_node_id = self.next_node_id();
729 let loop_hir_id = self.lower_node_id(loop_node_id);
731 let x_ident = Ident::with_dummy_span(sym::result);
732 let (x_pat, x_pat_hid) = self.pat_ident(gen_future_span, x_ident);
733 let x_expr = self.expr_ident(gen_future_span, x_ident, x_pat_hid);
734 let ready_field = self.single_pat_field(gen_future_span, x_pat);
735 let ready_pat = self.pat_lang_item_variant(
737 hir::LangItem::PollReady,
741 let break_x = self.with_loop_scope(loop_node_id, move |this| {
743 hir::ExprKind::Break(this.lower_loop_destination(None), Some(x_expr));
744 this.arena.alloc(this.expr(gen_future_span, expr_break, ThinVec::new()))
746 self.arm(ready_pat, break_x)
749 // `::std::task::Poll::Pending => {}`
751 let pending_pat = self.pat_lang_item_variant(
753 hir::LangItem::PollPending,
757 let empty_block = self.expr_block_empty(span);
758 self.arm(pending_pat, empty_block)
761 let inner_match_stmt = {
762 let match_expr = self.expr_match(
765 arena_vec![self; ready_arm, pending_arm],
766 hir::MatchSource::AwaitDesugar,
768 self.stmt_expr(span, match_expr)
771 // task_context = yield ();
773 let unit = self.expr_unit(span);
774 let yield_expr = self.expr(
776 hir::ExprKind::Yield(unit, hir::YieldSource::Await { expr: Some(expr_hir_id) }),
779 let yield_expr = self.arena.alloc(yield_expr);
781 if let Some(task_context_hid) = self.task_context {
782 let lhs = self.expr_ident(span, task_context_ident, task_context_hid);
783 let assign = self.expr(
785 hir::ExprKind::Assign(lhs, yield_expr, self.lower_span(span)),
788 self.stmt_expr(span, assign)
790 // Use of `await` outside of an async context. Return `yield_expr` so that we can
791 // proceed with type checking.
792 self.stmt(span, hir::StmtKind::Semi(yield_expr))
796 let loop_block = self.block_all(span, arena_vec![self; inner_match_stmt, yield_stmt], None);
799 let loop_expr = self.arena.alloc(hir::Expr {
801 kind: hir::ExprKind::Loop(
804 hir::LoopSource::Loop,
805 self.lower_span(span),
807 span: self.lower_span(span),
810 // mut __awaitee => loop { ... }
811 let awaitee_arm = self.arm(awaitee_pat, loop_expr);
813 // `match ::std::future::IntoFuture::into_future(<expr>) { ... }`
814 let into_future_span = self.mark_span_with_reason(
815 DesugaringKind::Await,
817 self.allow_into_future.clone(),
819 let into_future_expr = self.expr_call_lang_item_fn(
821 hir::LangItem::IntoFutureIntoFuture,
822 arena_vec![self; expr],
826 // match <into_future_expr> {
827 // mut __awaitee => loop { .. }
829 hir::ExprKind::Match(
831 arena_vec![self; awaitee_arm],
832 hir::MatchSource::AwaitDesugar,
836 fn lower_expr_closure(
838 binder: &ClosureBinder,
839 capture_clause: CaptureBy,
841 movability: Movability,
845 ) -> hir::ExprKind<'hir> {
846 let (binder_clause, generic_params) = self.lower_closure_binder(binder);
848 let (body_id, generator_option) = self.with_new_scopes(move |this| {
849 let prev = this.current_item;
850 this.current_item = Some(fn_decl_span);
851 let mut generator_kind = None;
852 let body_id = this.lower_fn_body(decl, |this| {
853 let e = this.lower_expr_mut(body);
854 generator_kind = this.generator_kind;
857 let generator_option =
858 this.generator_movability_for_fn(&decl, fn_decl_span, generator_kind, movability);
859 this.current_item = prev;
860 (body_id, generator_option)
863 self.with_lifetime_binder(closure_id, generic_params, |this, bound_generic_params| {
864 // Lower outside new scope to preserve `is_in_loop_condition`.
865 let fn_decl = this.lower_fn_decl(decl, None, FnDeclKind::Closure, None);
867 hir::ExprKind::Closure {
868 binder: binder_clause,
870 bound_generic_params,
873 fn_decl_span: this.lower_span(fn_decl_span),
874 movability: generator_option,
879 fn generator_movability_for_fn(
883 generator_kind: Option<hir::GeneratorKind>,
884 movability: Movability,
885 ) -> Option<hir::Movability> {
886 match generator_kind {
887 Some(hir::GeneratorKind::Gen) => {
888 if decl.inputs.len() > 1 {
893 "too many parameters for a generator (expected 0 or 1 parameters)"
899 Some(hir::GeneratorKind::Async(_)) => {
900 panic!("non-`async` closure body turned `async` during lowering");
903 if movability == Movability::Static {
908 "closures cannot be static"
917 fn lower_closure_binder<'c>(
919 binder: &'c ClosureBinder,
920 ) -> (&'hir hir::ClosureBinder, &'c [GenericParam]) {
921 let (binder, params) = match binder {
922 ClosureBinder::NotPresent => (hir::ClosureBinder::Default, &[][..]),
923 &ClosureBinder::For { span, ref generic_params } => {
924 let span = self.lower_span(span);
925 (hir::ClosureBinder::For { span }, &**generic_params)
929 (self.arena.alloc(binder), params)
932 fn lower_expr_async_closure(
934 binder: &ClosureBinder,
935 capture_clause: CaptureBy,
937 inner_closure_id: NodeId,
941 ) -> hir::ExprKind<'hir> {
942 if let &ClosureBinder::For { span, .. } = binder {
943 self.tcx.sess.span_err(
945 "`for<...>` binders on `async` closures are not currently supported",
949 let (binder_clause, generic_params) = self.lower_closure_binder(binder);
952 FnDecl { inputs: decl.inputs.clone(), output: FnRetTy::Default(fn_decl_span) };
954 let body = self.with_new_scopes(|this| {
955 // FIXME(cramertj): allow `async` non-`move` closures with arguments.
956 if capture_clause == CaptureBy::Ref && !decl.inputs.is_empty() {
961 "`async` non-`move` closures with parameters are not currently supported",
964 "consider using `let` statements to manually capture \
965 variables by reference before entering an `async move` closure",
970 // Transform `async |x: u8| -> X { ... }` into
971 // `|x: u8| future_from_generator(|| -> X { ... })`.
972 let body_id = this.lower_fn_body(&outer_decl, |this| {
974 if let FnRetTy::Ty(ty) = &decl.output { Some(ty.clone()) } else { None };
975 let async_body = this.make_async_expr(
980 hir::AsyncGeneratorKind::Closure,
981 |this| this.with_new_scopes(|this| this.lower_expr_mut(body)),
983 this.expr(fn_decl_span, async_body, ThinVec::new())
988 self.with_lifetime_binder(closure_id, generic_params, |this, bound_generic_params| {
989 // We need to lower the declaration outside the new scope, because we
990 // have to conserve the state of being inside a loop condition for the
991 // closure argument types.
992 let fn_decl = this.lower_fn_decl(&outer_decl, None, FnDeclKind::Closure, None);
994 hir::ExprKind::Closure {
995 binder: binder_clause,
997 bound_generic_params,
1000 fn_decl_span: this.lower_span(fn_decl_span),
1006 /// Destructure the LHS of complex assignments.
1007 /// For instance, lower `(a, b) = t` to `{ let (lhs1, lhs2) = t; a = lhs1; b = lhs2; }`.
1008 fn lower_expr_assign(
1014 ) -> hir::ExprKind<'hir> {
1015 // Return early in case of an ordinary assignment.
1016 fn is_ordinary(lower_ctx: &mut LoweringContext<'_, '_>, lhs: &Expr) -> bool {
1019 | ExprKind::Struct(..)
1021 | ExprKind::Underscore => false,
1022 // Check for tuple struct constructor.
1023 ExprKind::Call(callee, ..) => lower_ctx.extract_tuple_struct_path(callee).is_none(),
1024 ExprKind::Paren(e) => {
1026 // We special-case `(..)` for consistency with patterns.
1027 ExprKind::Range(None, None, RangeLimits::HalfOpen) => false,
1028 _ => is_ordinary(lower_ctx, e),
1034 if is_ordinary(self, lhs) {
1035 return hir::ExprKind::Assign(
1036 self.lower_expr(lhs),
1037 self.lower_expr(rhs),
1038 self.lower_span(eq_sign_span),
1042 let mut assignments = vec![];
1044 // The LHS becomes a pattern: `(lhs1, lhs2)`.
1045 let pat = self.destructure_assign(lhs, eq_sign_span, &mut assignments);
1046 let rhs = self.lower_expr(rhs);
1048 // Introduce a `let` for destructuring: `let (lhs1, lhs2) = t`.
1049 let destructure_let = self.stmt_let_pat(
1054 hir::LocalSource::AssignDesugar(self.lower_span(eq_sign_span)),
1057 // `a = lhs1; b = lhs2;`.
1060 .alloc_from_iter(std::iter::once(destructure_let).chain(assignments.into_iter()));
1062 // Wrap everything in a block.
1063 hir::ExprKind::Block(&self.block_all(whole_span, stmts, None), None)
1066 /// If the given expression is a path to a tuple struct, returns that path.
1067 /// It is not a complete check, but just tries to reject most paths early
1068 /// if they are not tuple structs.
1069 /// Type checking will take care of the full validation later.
1070 fn extract_tuple_struct_path<'a>(
1073 ) -> Option<(&'a Option<QSelf>, &'a Path)> {
1074 if let ExprKind::Path(qself, path) = &expr.kind {
1075 // Does the path resolve to something disallowed in a tuple struct/variant pattern?
1076 if let Some(partial_res) = self.resolver.get_partial_res(expr.id) {
1077 if partial_res.unresolved_segments() == 0
1078 && !partial_res.base_res().expected_in_tuple_struct_pat()
1083 return Some((qself, path));
1088 /// If the given expression is a path to a unit struct, returns that path.
1089 /// It is not a complete check, but just tries to reject most paths early
1090 /// if they are not unit structs.
1091 /// Type checking will take care of the full validation later.
1092 fn extract_unit_struct_path<'a>(
1095 ) -> Option<(&'a Option<QSelf>, &'a Path)> {
1096 if let ExprKind::Path(qself, path) = &expr.kind {
1097 // Does the path resolve to something disallowed in a unit struct/variant pattern?
1098 if let Some(partial_res) = self.resolver.get_partial_res(expr.id) {
1099 if partial_res.unresolved_segments() == 0
1100 && !partial_res.base_res().expected_in_unit_struct_pat()
1105 return Some((qself, path));
1110 /// Convert the LHS of a destructuring assignment to a pattern.
1111 /// Each sub-assignment is recorded in `assignments`.
1112 fn destructure_assign(
1116 assignments: &mut Vec<hir::Stmt<'hir>>,
1117 ) -> &'hir hir::Pat<'hir> {
1118 self.arena.alloc(self.destructure_assign_mut(lhs, eq_sign_span, assignments))
1121 fn destructure_assign_mut(
1125 assignments: &mut Vec<hir::Stmt<'hir>>,
1126 ) -> hir::Pat<'hir> {
1128 // Underscore pattern.
1129 ExprKind::Underscore => {
1130 return self.pat_without_dbm(lhs.span, hir::PatKind::Wild);
1133 ExprKind::Array(elements) => {
1135 self.destructure_sequence(elements, "slice", eq_sign_span, assignments);
1136 let slice_pat = if let Some((i, span)) = rest {
1137 let (before, after) = pats.split_at(i);
1138 hir::PatKind::Slice(
1140 Some(self.arena.alloc(self.pat_without_dbm(span, hir::PatKind::Wild))),
1144 hir::PatKind::Slice(pats, None, &[])
1146 return self.pat_without_dbm(lhs.span, slice_pat);
1149 ExprKind::Call(callee, args) => {
1150 if let Some((qself, path)) = self.extract_tuple_struct_path(callee) {
1151 let (pats, rest) = self.destructure_sequence(
1153 "tuple struct or variant",
1157 let qpath = self.lower_qpath(
1161 ParamMode::Optional,
1162 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1164 // Destructure like a tuple struct.
1165 let tuple_struct_pat =
1166 hir::PatKind::TupleStruct(qpath, pats, rest.map(|r| r.0));
1167 return self.pat_without_dbm(lhs.span, tuple_struct_pat);
1170 // Unit structs and enum variants.
1171 ExprKind::Path(..) => {
1172 if let Some((qself, path)) = self.extract_unit_struct_path(lhs) {
1173 let qpath = self.lower_qpath(
1177 ParamMode::Optional,
1178 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1180 // Destructure like a unit struct.
1181 let unit_struct_pat = hir::PatKind::Path(qpath);
1182 return self.pat_without_dbm(lhs.span, unit_struct_pat);
1186 ExprKind::Struct(se) => {
1187 let field_pats = self.arena.alloc_from_iter(se.fields.iter().map(|f| {
1188 let pat = self.destructure_assign(&f.expr, eq_sign_span, assignments);
1190 hir_id: self.next_id(),
1191 ident: self.lower_ident(f.ident),
1193 is_shorthand: f.is_shorthand,
1194 span: self.lower_span(f.span),
1197 let qpath = self.lower_qpath(
1201 ParamMode::Optional,
1202 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1204 let fields_omitted = match &se.rest {
1205 StructRest::Base(e) => {
1210 "functional record updates are not allowed in destructuring \
1215 "consider removing the trailing pattern",
1217 rustc_errors::Applicability::MachineApplicable,
1222 StructRest::Rest(_) => true,
1223 StructRest::None => false,
1225 let struct_pat = hir::PatKind::Struct(qpath, field_pats, fields_omitted);
1226 return self.pat_without_dbm(lhs.span, struct_pat);
1229 ExprKind::Tup(elements) => {
1231 self.destructure_sequence(elements, "tuple", eq_sign_span, assignments);
1232 let tuple_pat = hir::PatKind::Tuple(pats, rest.map(|r| r.0));
1233 return self.pat_without_dbm(lhs.span, tuple_pat);
1235 ExprKind::Paren(e) => {
1236 // We special-case `(..)` for consistency with patterns.
1237 if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
1238 let tuple_pat = hir::PatKind::Tuple(&[], Some(0));
1239 return self.pat_without_dbm(lhs.span, tuple_pat);
1241 return self.destructure_assign_mut(e, eq_sign_span, assignments);
1246 // Treat all other cases as normal lvalue.
1247 let ident = Ident::new(sym::lhs, self.lower_span(lhs.span));
1248 let (pat, binding) = self.pat_ident_mut(lhs.span, ident);
1249 let ident = self.expr_ident(lhs.span, ident, binding);
1251 hir::ExprKind::Assign(self.lower_expr(lhs), ident, self.lower_span(eq_sign_span));
1252 let expr = self.expr(lhs.span, assign, ThinVec::new());
1253 assignments.push(self.stmt_expr(lhs.span, expr));
1257 /// Destructure a sequence of expressions occurring on the LHS of an assignment.
1258 /// Such a sequence occurs in a tuple (struct)/slice.
1259 /// Return a sequence of corresponding patterns, and the index and the span of `..` if it
1261 /// Each sub-assignment is recorded in `assignments`.
1262 fn destructure_sequence(
1264 elements: &[AstP<Expr>],
1267 assignments: &mut Vec<hir::Stmt<'hir>>,
1268 ) -> (&'hir [hir::Pat<'hir>], Option<(usize, Span)>) {
1269 let mut rest = None;
1271 self.arena.alloc_from_iter(elements.iter().enumerate().filter_map(|(i, e)| {
1272 // Check for `..` pattern.
1273 if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
1274 if let Some((_, prev_span)) = rest {
1275 self.ban_extra_rest_pat(e.span, prev_span, ctx);
1277 rest = Some((i, e.span));
1281 Some(self.destructure_assign_mut(e, eq_sign_span, assignments))
1287 /// Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`.
1288 fn lower_expr_range_closed(&mut self, span: Span, e1: &Expr, e2: &Expr) -> hir::ExprKind<'hir> {
1289 let e1 = self.lower_expr_mut(e1);
1290 let e2 = self.lower_expr_mut(e2);
1292 hir::QPath::LangItem(hir::LangItem::RangeInclusiveNew, self.lower_span(span), None);
1294 self.arena.alloc(self.expr(span, hir::ExprKind::Path(fn_path), ThinVec::new()));
1295 hir::ExprKind::Call(fn_expr, arena_vec![self; e1, e2])
1298 fn lower_expr_range(
1304 ) -> hir::ExprKind<'hir> {
1305 use rustc_ast::RangeLimits::*;
1307 let lang_item = match (e1, e2, lims) {
1308 (None, None, HalfOpen) => hir::LangItem::RangeFull,
1309 (Some(..), None, HalfOpen) => hir::LangItem::RangeFrom,
1310 (None, Some(..), HalfOpen) => hir::LangItem::RangeTo,
1311 (Some(..), Some(..), HalfOpen) => hir::LangItem::Range,
1312 (None, Some(..), Closed) => hir::LangItem::RangeToInclusive,
1313 (Some(..), Some(..), Closed) => unreachable!(),
1314 (_, None, Closed) => self.diagnostic().span_fatal(span, "inclusive range with no end"),
1317 let fields = self.arena.alloc_from_iter(
1318 e1.iter().map(|e| (sym::start, e)).chain(e2.iter().map(|e| (sym::end, e))).map(
1320 let expr = self.lower_expr(&e);
1321 let ident = Ident::new(s, self.lower_span(e.span));
1322 self.expr_field(ident, expr, e.span)
1327 hir::ExprKind::Struct(
1328 self.arena.alloc(hir::QPath::LangItem(lang_item, self.lower_span(span), None)),
1334 fn lower_label(&self, opt_label: Option<Label>) -> Option<Label> {
1335 let label = opt_label?;
1336 Some(Label { ident: self.lower_ident(label.ident) })
1339 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
1340 let target_id = match destination {
1342 if let Some(loop_id) = self.resolver.get_label_res(id) {
1343 Ok(self.lower_node_id(loop_id))
1345 Err(hir::LoopIdError::UnresolvedLabel)
1350 .map(|id| Ok(self.lower_node_id(id)))
1351 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope)),
1353 let label = self.lower_label(destination.map(|(_, label)| label));
1354 hir::Destination { label, target_id }
1357 fn lower_jump_destination(&mut self, id: NodeId, opt_label: Option<Label>) -> hir::Destination {
1358 if self.is_in_loop_condition && opt_label.is_none() {
1361 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition),
1364 self.lower_loop_destination(opt_label.map(|label| (id, label)))
1368 fn with_catch_scope<T>(&mut self, catch_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1369 let old_scope = self.catch_scope.replace(catch_id);
1370 let result = f(self);
1371 self.catch_scope = old_scope;
1375 fn with_loop_scope<T>(&mut self, loop_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1376 // We're no longer in the base loop's condition; we're in another loop.
1377 let was_in_loop_condition = self.is_in_loop_condition;
1378 self.is_in_loop_condition = false;
1380 let old_scope = self.loop_scope.replace(loop_id);
1381 let result = f(self);
1382 self.loop_scope = old_scope;
1384 self.is_in_loop_condition = was_in_loop_condition;
1389 fn with_loop_condition_scope<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
1390 let was_in_loop_condition = self.is_in_loop_condition;
1391 self.is_in_loop_condition = true;
1393 let result = f(self);
1395 self.is_in_loop_condition = was_in_loop_condition;
1400 fn lower_expr_field(&mut self, f: &ExprField) -> hir::ExprField<'hir> {
1402 hir_id: self.next_id(),
1403 ident: self.lower_ident(f.ident),
1404 expr: self.lower_expr(&f.expr),
1405 span: self.lower_span(f.span),
1406 is_shorthand: f.is_shorthand,
1410 fn lower_expr_yield(&mut self, span: Span, opt_expr: Option<&Expr>) -> hir::ExprKind<'hir> {
1411 match self.generator_kind {
1412 Some(hir::GeneratorKind::Gen) => {}
1413 Some(hir::GeneratorKind::Async(_)) => {
1418 "`async` generators are not yet supported"
1422 None => self.generator_kind = Some(hir::GeneratorKind::Gen),
1426 opt_expr.as_ref().map(|x| self.lower_expr(x)).unwrap_or_else(|| self.expr_unit(span));
1428 hir::ExprKind::Yield(expr, hir::YieldSource::Yield)
1431 /// Desugar `ExprForLoop` from: `[opt_ident]: for <pat> in <head> <body>` into:
1432 /// ```ignore (pseudo-rust)
1434 /// let result = match IntoIterator::into_iter(<head>) {
1436 /// [opt_ident]: loop {
1437 /// match Iterator::next(&mut iter) {
1439 /// Some(<pat>) => <body>,
1453 opt_label: Option<Label>,
1454 ) -> hir::Expr<'hir> {
1455 let head = self.lower_expr_mut(head);
1456 let pat = self.lower_pat(pat);
1458 self.mark_span_with_reason(DesugaringKind::ForLoop, self.lower_span(e.span), None);
1459 let head_span = self.mark_span_with_reason(DesugaringKind::ForLoop, head.span, None);
1460 let pat_span = self.mark_span_with_reason(DesugaringKind::ForLoop, pat.span, None);
1465 self.with_loop_scope(e.id, |this| this.expr_break_alloc(for_span, ThinVec::new()));
1466 let pat = self.pat_none(for_span);
1467 self.arm(pat, break_expr)
1470 // Some(<pat>) => <body>,
1472 let some_pat = self.pat_some(pat_span, pat);
1473 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
1474 let body_expr = self.arena.alloc(self.expr_block(body_block, ThinVec::new()));
1475 self.arm(some_pat, body_expr)
1479 let iter = Ident::with_dummy_span(sym::iter);
1480 let (iter_pat, iter_pat_nid) =
1481 self.pat_ident_binding_mode(head_span, iter, hir::BindingAnnotation::Mutable);
1483 // `match Iterator::next(&mut iter) { ... }`
1485 let iter = self.expr_ident(head_span, iter, iter_pat_nid);
1486 let ref_mut_iter = self.expr_mut_addr_of(head_span, iter);
1487 let next_expr = self.expr_call_lang_item_fn(
1489 hir::LangItem::IteratorNext,
1490 arena_vec![self; ref_mut_iter],
1493 let arms = arena_vec![self; none_arm, some_arm];
1495 self.expr_match(head_span, next_expr, arms, hir::MatchSource::ForLoopDesugar)
1497 let match_stmt = self.stmt_expr(for_span, match_expr);
1499 let loop_block = self.block_all(for_span, arena_vec![self; match_stmt], None);
1501 // `[opt_ident]: loop { ... }`
1502 let kind = hir::ExprKind::Loop(
1504 self.lower_label(opt_label),
1505 hir::LoopSource::ForLoop,
1506 self.lower_span(for_span.with_hi(head.span.hi())),
1509 self.arena.alloc(hir::Expr { hir_id: self.lower_node_id(e.id), kind, span: for_span });
1511 // `mut iter => { ... }`
1512 let iter_arm = self.arm(iter_pat, loop_expr);
1514 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
1515 let into_iter_expr = {
1516 self.expr_call_lang_item_fn(
1518 hir::LangItem::IntoIterIntoIter,
1519 arena_vec![self; head],
1524 let match_expr = self.arena.alloc(self.expr_match(
1527 arena_vec![self; iter_arm],
1528 hir::MatchSource::ForLoopDesugar,
1531 let attrs: Vec<_> = e.attrs.iter().map(|a| self.lower_attr(a)).collect();
1533 // This is effectively `{ let _result = ...; _result }`.
1534 // The construct was introduced in #21984 and is necessary to make sure that
1535 // temporaries in the `head` expression are dropped and do not leak to the
1536 // surrounding scope of the `match` since the `match` is not a terminating scope.
1538 // Also, add the attributes to the outer returned expr node.
1539 self.expr_drop_temps_mut(for_span, match_expr, attrs.into())
1542 /// Desugar `ExprKind::Try` from: `<expr>?` into:
1543 /// ```ignore (pseudo-rust)
1544 /// match Try::branch(<expr>) {
1545 /// ControlFlow::Continue(val) => #[allow(unreachable_code)] val,,
1546 /// ControlFlow::Break(residual) =>
1547 /// #[allow(unreachable_code)]
1548 /// // If there is an enclosing `try {...}`:
1549 /// break 'catch_target Try::from_residual(residual),
1551 /// return Try::from_residual(residual),
1554 fn lower_expr_try(&mut self, span: Span, sub_expr: &Expr) -> hir::ExprKind<'hir> {
1555 let unstable_span = self.mark_span_with_reason(
1556 DesugaringKind::QuestionMark,
1558 self.allow_try_trait.clone(),
1560 let try_span = self.tcx.sess.source_map().end_point(span);
1561 let try_span = self.mark_span_with_reason(
1562 DesugaringKind::QuestionMark,
1564 self.allow_try_trait.clone(),
1567 // `Try::branch(<expr>)`
1570 let sub_expr = self.lower_expr_mut(sub_expr);
1572 self.expr_call_lang_item_fn(
1574 hir::LangItem::TryTraitBranch,
1575 arena_vec![self; sub_expr],
1580 // `#[allow(unreachable_code)]`
1582 // `allow(unreachable_code)`
1584 let allow_ident = Ident::new(sym::allow, self.lower_span(span));
1585 let uc_ident = Ident::new(sym::unreachable_code, self.lower_span(span));
1586 let uc_nested = attr::mk_nested_word_item(uc_ident);
1587 attr::mk_list_item(allow_ident, vec![uc_nested])
1589 attr::mk_attr_outer(allow)
1591 let attrs = vec![attr];
1593 // `ControlFlow::Continue(val) => #[allow(unreachable_code)] val,`
1594 let continue_arm = {
1595 let val_ident = Ident::with_dummy_span(sym::val);
1596 let (val_pat, val_pat_nid) = self.pat_ident(span, val_ident);
1597 let val_expr = self.arena.alloc(self.expr_ident_with_attrs(
1601 ThinVec::from(attrs.clone()),
1603 let continue_pat = self.pat_cf_continue(unstable_span, val_pat);
1604 self.arm(continue_pat, val_expr)
1607 // `ControlFlow::Break(residual) =>
1608 // #[allow(unreachable_code)]
1609 // return Try::from_residual(residual),`
1611 let residual_ident = Ident::with_dummy_span(sym::residual);
1612 let (residual_local, residual_local_nid) = self.pat_ident(try_span, residual_ident);
1613 let residual_expr = self.expr_ident_mut(try_span, residual_ident, residual_local_nid);
1614 let from_residual_expr = self.wrap_in_try_constructor(
1615 hir::LangItem::TryTraitFromResidual,
1617 self.arena.alloc(residual_expr),
1620 let thin_attrs = ThinVec::from(attrs);
1621 let ret_expr = if let Some(catch_node) = self.catch_scope {
1622 let target_id = Ok(self.lower_node_id(catch_node));
1623 self.arena.alloc(self.expr(
1625 hir::ExprKind::Break(
1626 hir::Destination { label: None, target_id },
1627 Some(from_residual_expr),
1632 self.arena.alloc(self.expr(
1634 hir::ExprKind::Ret(Some(from_residual_expr)),
1639 let break_pat = self.pat_cf_break(try_span, residual_local);
1640 self.arm(break_pat, ret_expr)
1643 hir::ExprKind::Match(
1645 arena_vec![self; break_arm, continue_arm],
1646 hir::MatchSource::TryDesugar,
1650 /// Desugar `ExprKind::Yeet` from: `do yeet <expr>` into:
1652 /// // If there is an enclosing `try {...}`:
1653 /// break 'catch_target FromResidual::from_residual(Yeet(residual)),
1655 /// return FromResidual::from_residual(Yeet(residual)),
1657 /// But to simplify this, there's a `from_yeet` lang item function which
1658 /// handles the combined `FromResidual::from_residual(Yeet(residual))`.
1659 fn lower_expr_yeet(&mut self, span: Span, sub_expr: Option<&Expr>) -> hir::ExprKind<'hir> {
1660 // The expression (if present) or `()` otherwise.
1661 let (yeeted_span, yeeted_expr) = if let Some(sub_expr) = sub_expr {
1662 (sub_expr.span, self.lower_expr(sub_expr))
1664 (self.mark_span_with_reason(DesugaringKind::YeetExpr, span, None), self.expr_unit(span))
1667 let unstable_span = self.mark_span_with_reason(
1668 DesugaringKind::YeetExpr,
1670 self.allow_try_trait.clone(),
1673 let from_yeet_expr = self.wrap_in_try_constructor(
1674 hir::LangItem::TryTraitFromYeet,
1680 if let Some(catch_node) = self.catch_scope {
1681 let target_id = Ok(self.lower_node_id(catch_node));
1682 hir::ExprKind::Break(hir::Destination { label: None, target_id }, Some(from_yeet_expr))
1684 hir::ExprKind::Ret(Some(from_yeet_expr))
1688 // =========================================================================
1689 // Helper methods for building HIR.
1690 // =========================================================================
1692 /// Wrap the given `expr` in a terminating scope using `hir::ExprKind::DropTemps`.
1694 /// In terms of drop order, it has the same effect as wrapping `expr` in
1695 /// `{ let _t = $expr; _t }` but should provide better compile-time performance.
1697 /// The drop order can be important in e.g. `if expr { .. }`.
1698 pub(super) fn expr_drop_temps(
1701 expr: &'hir hir::Expr<'hir>,
1703 ) -> &'hir hir::Expr<'hir> {
1704 self.arena.alloc(self.expr_drop_temps_mut(span, expr, attrs))
1707 pub(super) fn expr_drop_temps_mut(
1710 expr: &'hir hir::Expr<'hir>,
1712 ) -> hir::Expr<'hir> {
1713 self.expr(span, hir::ExprKind::DropTemps(expr), attrs)
1719 arg: &'hir hir::Expr<'hir>,
1720 arms: &'hir [hir::Arm<'hir>],
1721 source: hir::MatchSource,
1722 ) -> hir::Expr<'hir> {
1723 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
1726 fn expr_break(&mut self, span: Span, attrs: AttrVec) -> hir::Expr<'hir> {
1727 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
1728 self.expr(span, expr_break, attrs)
1731 fn expr_break_alloc(&mut self, span: Span, attrs: AttrVec) -> &'hir hir::Expr<'hir> {
1732 let expr_break = self.expr_break(span, attrs);
1733 self.arena.alloc(expr_break)
1736 fn expr_mut_addr_of(&mut self, span: Span, e: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
1739 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Mut, e),
1744 fn expr_unit(&mut self, sp: Span) -> &'hir hir::Expr<'hir> {
1745 self.arena.alloc(self.expr(sp, hir::ExprKind::Tup(&[]), ThinVec::new()))
1751 e: &'hir hir::Expr<'hir>,
1752 args: &'hir [hir::Expr<'hir>],
1753 ) -> hir::Expr<'hir> {
1754 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
1760 e: &'hir hir::Expr<'hir>,
1761 args: &'hir [hir::Expr<'hir>],
1762 ) -> &'hir hir::Expr<'hir> {
1763 self.arena.alloc(self.expr_call_mut(span, e, args))
1766 fn expr_call_lang_item_fn_mut(
1769 lang_item: hir::LangItem,
1770 args: &'hir [hir::Expr<'hir>],
1771 hir_id: Option<hir::HirId>,
1772 ) -> hir::Expr<'hir> {
1774 self.arena.alloc(self.expr_lang_item_path(span, lang_item, ThinVec::new(), hir_id));
1775 self.expr_call_mut(span, path, args)
1778 fn expr_call_lang_item_fn(
1781 lang_item: hir::LangItem,
1782 args: &'hir [hir::Expr<'hir>],
1783 hir_id: Option<hir::HirId>,
1784 ) -> &'hir hir::Expr<'hir> {
1785 self.arena.alloc(self.expr_call_lang_item_fn_mut(span, lang_item, args, hir_id))
1788 fn expr_lang_item_path(
1791 lang_item: hir::LangItem,
1793 hir_id: Option<hir::HirId>,
1794 ) -> hir::Expr<'hir> {
1797 hir::ExprKind::Path(hir::QPath::LangItem(lang_item, self.lower_span(span), hir_id)),
1802 pub(super) fn expr_ident(
1806 binding: hir::HirId,
1807 ) -> &'hir hir::Expr<'hir> {
1808 self.arena.alloc(self.expr_ident_mut(sp, ident, binding))
1811 pub(super) fn expr_ident_mut(
1815 binding: hir::HirId,
1816 ) -> hir::Expr<'hir> {
1817 self.expr_ident_with_attrs(sp, ident, binding, ThinVec::new())
1820 fn expr_ident_with_attrs(
1824 binding: hir::HirId,
1826 ) -> hir::Expr<'hir> {
1827 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
1829 self.arena.alloc(hir::Path {
1830 span: self.lower_span(span),
1831 res: Res::Local(binding),
1832 segments: arena_vec![self; hir::PathSegment::from_ident(ident)],
1836 self.expr(span, expr_path, attrs)
1839 fn expr_unsafe(&mut self, expr: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
1840 let hir_id = self.next_id();
1841 let span = expr.span;
1844 hir::ExprKind::Block(
1845 self.arena.alloc(hir::Block {
1849 rules: hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::CompilerGenerated),
1850 span: self.lower_span(span),
1851 targeted_by_break: false,
1859 fn expr_block_empty(&mut self, span: Span) -> &'hir hir::Expr<'hir> {
1860 let blk = self.block_all(span, &[], None);
1861 let expr = self.expr_block(blk, ThinVec::new());
1862 self.arena.alloc(expr)
1865 pub(super) fn expr_block(
1867 b: &'hir hir::Block<'hir>,
1869 ) -> hir::Expr<'hir> {
1870 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
1876 kind: hir::ExprKind<'hir>,
1878 ) -> hir::Expr<'hir> {
1879 let hir_id = self.next_id();
1880 self.lower_attrs(hir_id, &attrs);
1881 hir::Expr { hir_id, kind, span: self.lower_span(span) }
1887 expr: &'hir hir::Expr<'hir>,
1889 ) -> hir::ExprField<'hir> {
1891 hir_id: self.next_id(),
1893 span: self.lower_span(span),
1895 is_shorthand: false,
1899 fn arm(&mut self, pat: &'hir hir::Pat<'hir>, expr: &'hir hir::Expr<'hir>) -> hir::Arm<'hir> {
1901 hir_id: self.next_id(),
1904 span: self.lower_span(expr.span),