1 use crate::{FnDeclKind, ImplTraitPosition};
3 use super::{ImplTraitContext, LoweringContext, ParamMode, ParenthesizedGenericArgs};
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::hygiene::ExpnId;
15 use rustc_span::source_map::{respan, DesugaringKind, Span, Spanned};
16 use rustc_span::symbol::{sym, Ident};
17 use rustc_span::DUMMY_SP;
19 impl<'hir> LoweringContext<'_, 'hir> {
20 fn lower_exprs(&mut self, exprs: &[AstP<Expr>]) -> &'hir [hir::Expr<'hir>] {
21 self.arena.alloc_from_iter(exprs.iter().map(|x| self.lower_expr_mut(x)))
24 pub(super) fn lower_expr(&mut self, e: &Expr) -> &'hir hir::Expr<'hir> {
25 self.arena.alloc(self.lower_expr_mut(e))
28 pub(super) fn lower_expr_mut(&mut self, e: &Expr) -> hir::Expr<'hir> {
29 ensure_sufficient_stack(|| {
30 let kind = match e.kind {
31 ExprKind::Box(ref inner) => hir::ExprKind::Box(self.lower_expr(inner)),
32 ExprKind::Array(ref exprs) => hir::ExprKind::Array(self.lower_exprs(exprs)),
33 ExprKind::ConstBlock(ref anon_const) => {
34 let anon_const = self.lower_anon_const(anon_const);
35 hir::ExprKind::ConstBlock(anon_const)
37 ExprKind::Repeat(ref expr, ref count) => {
38 let expr = self.lower_expr(expr);
39 let count = self.lower_array_length(count);
40 hir::ExprKind::Repeat(expr, count)
42 ExprKind::Tup(ref elts) => hir::ExprKind::Tup(self.lower_exprs(elts)),
43 ExprKind::Call(ref f, ref args) => {
44 if let Some(legacy_args) = self.resolver.legacy_const_generic_args(f) {
45 self.lower_legacy_const_generics((**f).clone(), args.clone(), &legacy_args)
47 let f = self.lower_expr(f);
48 hir::ExprKind::Call(f, self.lower_exprs(args))
51 ExprKind::MethodCall(ref seg, ref args, span) => {
52 let hir_seg = self.arena.alloc(self.lower_path_segment(
57 ParenthesizedGenericArgs::Err,
58 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
60 let args = self.lower_exprs(args);
61 hir::ExprKind::MethodCall(hir_seg, args, self.lower_span(span))
63 ExprKind::Binary(binop, ref lhs, ref rhs) => {
64 let binop = self.lower_binop(binop);
65 let lhs = self.lower_expr(lhs);
66 let rhs = self.lower_expr(rhs);
67 hir::ExprKind::Binary(binop, lhs, rhs)
69 ExprKind::Unary(op, ref ohs) => {
70 let op = self.lower_unop(op);
71 let ohs = self.lower_expr(ohs);
72 hir::ExprKind::Unary(op, ohs)
74 ExprKind::Lit(ref l) => {
75 hir::ExprKind::Lit(respan(self.lower_span(l.span), l.kind.clone()))
77 ExprKind::Cast(ref expr, ref ty) => {
78 let expr = self.lower_expr(expr);
80 self.lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type));
81 hir::ExprKind::Cast(expr, ty)
83 ExprKind::Type(ref expr, ref ty) => {
84 let expr = self.lower_expr(expr);
86 self.lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type));
87 hir::ExprKind::Type(expr, ty)
89 ExprKind::AddrOf(k, m, ref ohs) => {
90 let ohs = self.lower_expr(ohs);
91 hir::ExprKind::AddrOf(k, m, ohs)
93 ExprKind::Let(ref pat, ref scrutinee, span) => {
94 hir::ExprKind::Let(self.arena.alloc(hir::Let {
95 hir_id: self.next_id(),
96 span: self.lower_span(span),
97 pat: self.lower_pat(pat),
99 init: self.lower_expr(scrutinee),
102 ExprKind::If(ref cond, ref then, ref else_opt) => {
103 self.lower_expr_if(cond, then, else_opt.as_deref())
105 ExprKind::While(ref cond, ref body, opt_label) => {
106 self.with_loop_scope(e.id, |this| {
108 this.mark_span_with_reason(DesugaringKind::WhileLoop, e.span, None);
109 this.lower_expr_while_in_loop_scope(span, cond, body, opt_label)
112 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
114 this.lower_block(body, false),
115 this.lower_label(opt_label),
116 hir::LoopSource::Loop,
120 ExprKind::TryBlock(ref body) => self.lower_expr_try_block(body),
121 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
122 self.lower_expr(expr),
123 self.arena.alloc_from_iter(arms.iter().map(|x| self.lower_arm(x))),
124 hir::MatchSource::Normal,
126 ExprKind::Async(capture_clause, closure_node_id, ref block) => self
132 hir::AsyncGeneratorKind::Block,
133 |this| this.with_new_scopes(|this| this.lower_block_expr(block)),
135 ExprKind::Await(ref expr) => {
136 let span = if expr.span.hi() < e.span.hi() {
137 expr.span.shrink_to_hi().with_hi(e.span.hi())
139 // this is a recovered `await expr`
142 self.lower_expr_await(span, expr)
152 if let Async::Yes { closure_id, .. } = asyncness {
153 self.lower_expr_async_closure(
161 self.lower_expr_closure(
170 ExprKind::Block(ref blk, opt_label) => {
171 let opt_label = self.lower_label(opt_label);
172 hir::ExprKind::Block(self.lower_block(blk, opt_label.is_some()), opt_label)
174 ExprKind::Assign(ref el, ref er, span) => {
175 self.lower_expr_assign(el, er, span, e.span)
177 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
178 self.lower_binop(op),
182 ExprKind::Field(ref el, ident) => {
183 hir::ExprKind::Field(self.lower_expr(el), self.lower_ident(ident))
185 ExprKind::Index(ref el, ref er) => {
186 hir::ExprKind::Index(self.lower_expr(el), self.lower_expr(er))
188 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
189 self.lower_expr_range_closed(e.span, e1, e2)
191 ExprKind::Range(ref e1, ref e2, lims) => {
192 self.lower_expr_range(e.span, e1.as_deref(), e2.as_deref(), lims)
194 ExprKind::Underscore => {
198 "in expressions, `_` can only be used on the left-hand side of an assignment",
200 .span_label(e.span, "`_` not allowed here")
204 ExprKind::Path(ref qself, ref path) => {
205 let qpath = self.lower_qpath(
210 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
212 hir::ExprKind::Path(qpath)
214 ExprKind::Break(opt_label, ref opt_expr) => {
215 let opt_expr = opt_expr.as_ref().map(|x| self.lower_expr(x));
216 hir::ExprKind::Break(self.lower_jump_destination(e.id, opt_label), opt_expr)
218 ExprKind::Continue(opt_label) => {
219 hir::ExprKind::Continue(self.lower_jump_destination(e.id, opt_label))
221 ExprKind::Ret(ref e) => {
222 let e = e.as_ref().map(|x| self.lower_expr(x));
223 hir::ExprKind::Ret(e)
225 ExprKind::InlineAsm(ref asm) => {
226 hir::ExprKind::InlineAsm(self.lower_inline_asm(e.span, asm))
228 ExprKind::Struct(ref se) => {
229 let rest = match &se.rest {
230 StructRest::Base(e) => Some(self.lower_expr(e)),
231 StructRest::Rest(sp) => {
233 .struct_span_err(*sp, "base expression required after `..`")
234 .span_label(*sp, "add a base expression here")
236 Some(&*self.arena.alloc(self.expr_err(*sp)))
238 StructRest::None => None,
240 hir::ExprKind::Struct(
241 self.arena.alloc(self.lower_qpath(
246 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
249 .alloc_from_iter(se.fields.iter().map(|x| self.lower_expr_field(x))),
253 ExprKind::Yield(ref opt_expr) => self.lower_expr_yield(e.span, opt_expr.as_deref()),
254 ExprKind::Err => hir::ExprKind::Err,
255 ExprKind::Try(ref sub_expr) => self.lower_expr_try(e.span, sub_expr),
256 ExprKind::Paren(ref ex) => {
257 let mut ex = self.lower_expr_mut(ex);
258 // Include parens in span, but only if it is a super-span.
259 if e.span.contains(ex.span) {
260 ex.span = self.lower_span(e.span);
262 // Merge attributes into the inner expression.
263 if !e.attrs.is_empty() {
265 self.attrs.get(&ex.hir_id.local_id).map(|la| *la).unwrap_or(&[]);
268 &*self.arena.alloc_from_iter(
271 .map(|a| self.lower_attr(a))
272 .chain(old_attrs.iter().cloned()),
279 // Desugar `ExprForLoop`
280 // from: `[opt_ident]: for <pat> in <head> <body>`
281 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
282 return self.lower_expr_for(e, pat, head, body, opt_label);
284 ExprKind::MacCall(_) => panic!("{:?} shouldn't exist here", e.span),
287 let hir_id = self.lower_node_id(e.id);
288 self.lower_attrs(hir_id, &e.attrs);
289 hir::Expr { hir_id, kind, span: self.lower_span(e.span) }
293 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
295 UnOp::Deref => hir::UnOp::Deref,
296 UnOp::Not => hir::UnOp::Not,
297 UnOp::Neg => hir::UnOp::Neg,
301 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
304 BinOpKind::Add => hir::BinOpKind::Add,
305 BinOpKind::Sub => hir::BinOpKind::Sub,
306 BinOpKind::Mul => hir::BinOpKind::Mul,
307 BinOpKind::Div => hir::BinOpKind::Div,
308 BinOpKind::Rem => hir::BinOpKind::Rem,
309 BinOpKind::And => hir::BinOpKind::And,
310 BinOpKind::Or => hir::BinOpKind::Or,
311 BinOpKind::BitXor => hir::BinOpKind::BitXor,
312 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
313 BinOpKind::BitOr => hir::BinOpKind::BitOr,
314 BinOpKind::Shl => hir::BinOpKind::Shl,
315 BinOpKind::Shr => hir::BinOpKind::Shr,
316 BinOpKind::Eq => hir::BinOpKind::Eq,
317 BinOpKind::Lt => hir::BinOpKind::Lt,
318 BinOpKind::Le => hir::BinOpKind::Le,
319 BinOpKind::Ne => hir::BinOpKind::Ne,
320 BinOpKind::Ge => hir::BinOpKind::Ge,
321 BinOpKind::Gt => hir::BinOpKind::Gt,
323 span: self.lower_span(b.span),
327 fn lower_legacy_const_generics(
330 args: Vec<AstP<Expr>>,
331 legacy_args_idx: &[usize],
332 ) -> hir::ExprKind<'hir> {
333 let ExprKind::Path(None, ref mut path) = f.kind else {
337 // Split the arguments into const generics and normal arguments
338 let mut real_args = vec![];
339 let mut generic_args = vec![];
340 for (idx, arg) in args.into_iter().enumerate() {
341 if legacy_args_idx.contains(&idx) {
342 let parent_def_id = self.current_hir_id_owner;
343 let node_id = self.resolver.next_node_id();
345 // Add a definition for the in-band const def.
346 self.resolver.create_def(
349 DefPathData::AnonConst,
354 let anon_const = AnonConst { id: node_id, value: arg };
355 generic_args.push(AngleBracketedArg::Arg(GenericArg::Const(anon_const)));
361 // Add generic args to the last element of the path.
362 let last_segment = path.segments.last_mut().unwrap();
363 assert!(last_segment.args.is_none());
364 last_segment.args = Some(AstP(GenericArgs::AngleBracketed(AngleBracketedArgs {
369 // Now lower everything as normal.
370 let f = self.lower_expr(&f);
371 hir::ExprKind::Call(f, self.lower_exprs(&real_args))
378 else_opt: Option<&Expr>,
379 ) -> hir::ExprKind<'hir> {
380 let lowered_cond = self.lower_expr(cond);
381 let new_cond = self.manage_let_cond(lowered_cond);
382 let then_expr = self.lower_block_expr(then);
383 if let Some(rslt) = else_opt {
384 hir::ExprKind::If(new_cond, self.arena.alloc(then_expr), Some(self.lower_expr(rslt)))
386 hir::ExprKind::If(new_cond, self.arena.alloc(then_expr), None)
390 // If `cond` kind is `let`, returns `let`. Otherwise, wraps and returns `cond`
391 // in a temporary block.
392 fn manage_let_cond(&mut self, cond: &'hir hir::Expr<'hir>) -> &'hir hir::Expr<'hir> {
393 fn has_let_expr<'hir>(expr: &'hir hir::Expr<'hir>) -> bool {
395 hir::ExprKind::Binary(_, lhs, rhs) => has_let_expr(lhs) || has_let_expr(rhs),
396 hir::ExprKind::Let(..) => true,
400 if has_let_expr(cond) {
403 let reason = DesugaringKind::CondTemporary;
404 let span_block = self.mark_span_with_reason(reason, cond.span, None);
405 self.expr_drop_temps(span_block, cond, AttrVec::new())
409 // We desugar: `'label: while $cond $body` into:
413 // if { let _t = $cond; _t } {
422 // Wrap in a construct equivalent to `{ let _t = $cond; _t }`
423 // to preserve drop semantics since `while $cond { ... }` does not
424 // let temporaries live outside of `cond`.
425 fn lower_expr_while_in_loop_scope(
430 opt_label: Option<Label>,
431 ) -> hir::ExprKind<'hir> {
432 let lowered_cond = self.with_loop_condition_scope(|t| t.lower_expr(cond));
433 let new_cond = self.manage_let_cond(lowered_cond);
434 let then = self.lower_block_expr(body);
435 let expr_break = self.expr_break(span, ThinVec::new());
436 let stmt_break = self.stmt_expr(span, expr_break);
437 let else_blk = self.block_all(span, arena_vec![self; stmt_break], None);
438 let else_expr = self.arena.alloc(self.expr_block(else_blk, ThinVec::new()));
439 let if_kind = hir::ExprKind::If(new_cond, self.arena.alloc(then), Some(else_expr));
440 let if_expr = self.expr(span, if_kind, ThinVec::new());
441 let block = self.block_expr(self.arena.alloc(if_expr));
442 let span = self.lower_span(span.with_hi(cond.span.hi()));
443 let opt_label = self.lower_label(opt_label);
444 hir::ExprKind::Loop(block, opt_label, hir::LoopSource::While, span)
447 /// Desugar `try { <stmts>; <expr> }` into `{ <stmts>; ::std::ops::Try::from_output(<expr>) }`,
448 /// `try { <stmts>; }` into `{ <stmts>; ::std::ops::Try::from_output(()) }`
449 /// and save the block id to use it as a break target for desugaring of the `?` operator.
450 fn lower_expr_try_block(&mut self, body: &Block) -> hir::ExprKind<'hir> {
451 self.with_catch_scope(body.id, |this| {
452 let mut block = this.lower_block_noalloc(body, true);
454 // Final expression of the block (if present) or `()` with span at the end of block
455 let (try_span, tail_expr) = if let Some(expr) = block.expr.take() {
457 this.mark_span_with_reason(
458 DesugaringKind::TryBlock,
460 this.allow_try_trait.clone(),
465 let try_span = this.mark_span_with_reason(
466 DesugaringKind::TryBlock,
467 this.sess.source_map().end_point(body.span),
468 this.allow_try_trait.clone(),
471 (try_span, this.expr_unit(try_span))
474 let ok_wrapped_span =
475 this.mark_span_with_reason(DesugaringKind::TryBlock, tail_expr.span, None);
477 // `::std::ops::Try::from_output($tail_expr)`
478 block.expr = Some(this.wrap_in_try_constructor(
479 hir::LangItem::TryTraitFromOutput,
485 hir::ExprKind::Block(this.arena.alloc(block), None)
489 fn wrap_in_try_constructor(
491 lang_item: hir::LangItem,
493 expr: &'hir hir::Expr<'hir>,
495 ) -> &'hir hir::Expr<'hir> {
496 let constructor = self.arena.alloc(self.expr_lang_item_path(
502 self.expr_call(overall_span, constructor, std::slice::from_ref(expr))
505 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm<'hir> {
506 let pat = self.lower_pat(&arm.pat);
507 let guard = arm.guard.as_ref().map(|cond| {
508 if let ExprKind::Let(ref pat, ref scrutinee, _) = cond.kind {
509 hir::Guard::IfLet(self.lower_pat(pat), self.lower_expr(scrutinee))
511 hir::Guard::If(self.lower_expr(cond))
514 let hir_id = self.next_id();
515 self.lower_attrs(hir_id, &arm.attrs);
520 body: self.lower_expr(&arm.body),
521 span: self.lower_span(arm.span),
525 /// Lower an `async` construct to a generator that is then wrapped so it implements `Future`.
530 /// std::future::from_generator(static move? |_task_context| -> <ret_ty> {
534 pub(super) fn make_async_expr(
536 capture_clause: CaptureBy,
537 closure_node_id: NodeId,
538 ret_ty: Option<AstP<Ty>>,
540 async_gen_kind: hir::AsyncGeneratorKind,
541 body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
542 ) -> hir::ExprKind<'hir> {
543 let output = match ret_ty {
544 Some(ty) => hir::FnRetTy::Return(
545 self.lower_ty(&ty, ImplTraitContext::Disallowed(ImplTraitPosition::AsyncBlock)),
547 None => hir::FnRetTy::DefaultReturn(self.lower_span(span)),
550 // Resume argument type. We let the compiler infer this to simplify the lowering. It is
551 // fully constrained by `future::from_generator`.
552 let input_ty = hir::Ty {
553 hir_id: self.next_id(),
554 kind: hir::TyKind::Infer,
555 span: self.lower_span(span),
558 // The closure/generator `FnDecl` takes a single (resume) argument of type `input_ty`.
559 let decl = self.arena.alloc(hir::FnDecl {
560 inputs: arena_vec![self; input_ty],
563 implicit_self: hir::ImplicitSelfKind::None,
566 // Lower the argument pattern/ident. The ident is used again in the `.await` lowering.
567 let (pat, task_context_hid) = self.pat_ident_binding_mode(
569 Ident::with_dummy_span(sym::_task_context),
570 hir::BindingAnnotation::Mutable,
572 let param = hir::Param {
573 hir_id: self.next_id(),
575 ty_span: self.lower_span(span),
576 span: self.lower_span(span),
578 let params = arena_vec![self; param];
580 let body_id = self.lower_body(move |this| {
581 this.generator_kind = Some(hir::GeneratorKind::Async(async_gen_kind));
583 let old_ctx = this.task_context;
584 this.task_context = Some(task_context_hid);
585 let res = body(this);
586 this.task_context = old_ctx;
590 // `static |_task_context| -> <ret_ty> { body }`:
591 let generator_kind = hir::ExprKind::Closure(
595 self.lower_span(span),
596 Some(hir::Movability::Static),
598 let generator = hir::Expr {
599 hir_id: self.lower_node_id(closure_node_id),
600 kind: generator_kind,
601 span: self.lower_span(span),
604 // `future::from_generator`:
606 self.mark_span_with_reason(DesugaringKind::Async, span, self.allow_gen_future.clone());
607 let gen_future = self.expr_lang_item_path(
609 hir::LangItem::FromGenerator,
614 // `future::from_generator(generator)`:
615 hir::ExprKind::Call(self.arena.alloc(gen_future), arena_vec![self; generator])
618 /// Desugar `<expr>.await` into:
620 /// match ::std::future::IntoFuture::into_future(<expr>) {
621 /// mut pinned => loop {
622 /// match unsafe { ::std::future::Future::poll(
623 /// <::std::pin::Pin>::new_unchecked(&mut pinned),
624 /// ::std::future::get_context(task_context),
626 /// ::std::task::Poll::Ready(result) => break result,
627 /// ::std::task::Poll::Pending => {}
629 /// task_context = yield ();
633 fn lower_expr_await(&mut self, dot_await_span: Span, expr: &Expr) -> hir::ExprKind<'hir> {
634 let full_span = expr.span.to(dot_await_span);
635 match self.generator_kind {
636 Some(hir::GeneratorKind::Async(_)) => {}
637 Some(hir::GeneratorKind::Gen) | None => {
638 let mut err = struct_span_err!(
642 "`await` is only allowed inside `async` functions and blocks"
644 err.span_label(dot_await_span, "only allowed inside `async` functions and blocks");
645 if let Some(item_sp) = self.current_item {
646 err.span_label(item_sp, "this is not `async`");
651 let span = self.mark_span_with_reason(DesugaringKind::Await, dot_await_span, None);
652 let gen_future_span = self.mark_span_with_reason(
653 DesugaringKind::Await,
655 self.allow_gen_future.clone(),
657 let expr = self.lower_expr_mut(expr);
658 let expr_hir_id = expr.hir_id;
660 let pinned_ident = Ident::with_dummy_span(sym::pinned);
661 let (pinned_pat, pinned_pat_hid) =
662 self.pat_ident_binding_mode(span, pinned_ident, hir::BindingAnnotation::Mutable);
664 let task_context_ident = Ident::with_dummy_span(sym::_task_context);
667 // ::std::future::Future::poll(
668 // ::std::pin::Pin::new_unchecked(&mut pinned),
669 // ::std::future::get_context(task_context),
673 let pinned = self.expr_ident(span, pinned_ident, pinned_pat_hid);
674 let ref_mut_pinned = self.expr_mut_addr_of(span, pinned);
675 let task_context = if let Some(task_context_hid) = self.task_context {
676 self.expr_ident_mut(span, task_context_ident, task_context_hid)
678 // Use of `await` outside of an async context, we cannot use `task_context` here.
681 let new_unchecked = self.expr_call_lang_item_fn_mut(
683 hir::LangItem::PinNewUnchecked,
684 arena_vec![self; ref_mut_pinned],
687 let get_context = self.expr_call_lang_item_fn_mut(
689 hir::LangItem::GetContext,
690 arena_vec![self; task_context],
693 let call = self.expr_call_lang_item_fn(
695 hir::LangItem::FuturePoll,
696 arena_vec![self; new_unchecked, get_context],
699 self.arena.alloc(self.expr_unsafe(call))
702 // `::std::task::Poll::Ready(result) => break result`
703 let loop_node_id = self.resolver.next_node_id();
704 let loop_hir_id = self.lower_node_id(loop_node_id);
706 let x_ident = Ident::with_dummy_span(sym::result);
707 let (x_pat, x_pat_hid) = self.pat_ident(gen_future_span, x_ident);
708 let x_expr = self.expr_ident(gen_future_span, x_ident, x_pat_hid);
709 let ready_field = self.single_pat_field(gen_future_span, x_pat);
710 let ready_pat = self.pat_lang_item_variant(
712 hir::LangItem::PollReady,
716 let break_x = self.with_loop_scope(loop_node_id, move |this| {
718 hir::ExprKind::Break(this.lower_loop_destination(None), Some(x_expr));
719 this.arena.alloc(this.expr(gen_future_span, expr_break, ThinVec::new()))
721 self.arm(ready_pat, break_x)
724 // `::std::task::Poll::Pending => {}`
726 let pending_pat = self.pat_lang_item_variant(
728 hir::LangItem::PollPending,
732 let empty_block = self.expr_block_empty(span);
733 self.arm(pending_pat, empty_block)
736 let inner_match_stmt = {
737 let match_expr = self.expr_match(
740 arena_vec![self; ready_arm, pending_arm],
741 hir::MatchSource::AwaitDesugar,
743 self.stmt_expr(span, match_expr)
746 // task_context = yield ();
748 let unit = self.expr_unit(span);
749 let yield_expr = self.expr(
751 hir::ExprKind::Yield(unit, hir::YieldSource::Await { expr: Some(expr_hir_id) }),
754 let yield_expr = self.arena.alloc(yield_expr);
756 if let Some(task_context_hid) = self.task_context {
757 let lhs = self.expr_ident(span, task_context_ident, task_context_hid);
758 let assign = self.expr(
760 hir::ExprKind::Assign(lhs, yield_expr, self.lower_span(span)),
763 self.stmt_expr(span, assign)
765 // Use of `await` outside of an async context. Return `yield_expr` so that we can
766 // proceed with type checking.
767 self.stmt(span, hir::StmtKind::Semi(yield_expr))
771 let loop_block = self.block_all(span, arena_vec![self; inner_match_stmt, yield_stmt], None);
774 let loop_expr = self.arena.alloc(hir::Expr {
776 kind: hir::ExprKind::Loop(
779 hir::LoopSource::Loop,
780 self.lower_span(span),
782 span: self.lower_span(span),
785 // mut pinned => loop { ... }
786 let pinned_arm = self.arm(pinned_pat, loop_expr);
788 // `match ::std::future::IntoFuture::into_future(<expr>) { ... }`
789 let into_future_span = self.mark_span_with_reason(
790 DesugaringKind::Await,
792 self.allow_into_future.clone(),
794 let into_future_expr = self.expr_call_lang_item_fn(
796 hir::LangItem::IntoFutureIntoFuture,
797 arena_vec![self; expr],
801 // match <into_future_expr> {
802 // mut pinned => loop { .. }
804 hir::ExprKind::Match(
806 arena_vec![self; pinned_arm],
807 hir::MatchSource::AwaitDesugar,
811 fn lower_expr_closure(
813 capture_clause: CaptureBy,
814 movability: Movability,
818 ) -> hir::ExprKind<'hir> {
819 let (body_id, generator_option) = self.with_new_scopes(move |this| {
820 let prev = this.current_item;
821 this.current_item = Some(fn_decl_span);
822 let mut generator_kind = None;
823 let body_id = this.lower_fn_body(decl, |this| {
824 let e = this.lower_expr_mut(body);
825 generator_kind = this.generator_kind;
828 let generator_option =
829 this.generator_movability_for_fn(&decl, fn_decl_span, generator_kind, movability);
830 this.current_item = prev;
831 (body_id, generator_option)
834 // Lower outside new scope to preserve `is_in_loop_condition`.
835 let fn_decl = self.lower_fn_decl(decl, None, FnDeclKind::Closure, None);
837 hir::ExprKind::Closure(
841 self.lower_span(fn_decl_span),
846 fn generator_movability_for_fn(
850 generator_kind: Option<hir::GeneratorKind>,
851 movability: Movability,
852 ) -> Option<hir::Movability> {
853 match generator_kind {
854 Some(hir::GeneratorKind::Gen) => {
855 if decl.inputs.len() > 1 {
860 "too many parameters for a generator (expected 0 or 1 parameters)"
866 Some(hir::GeneratorKind::Async(_)) => {
867 panic!("non-`async` closure body turned `async` during lowering");
870 if movability == Movability::Static {
871 struct_span_err!(self.sess, fn_decl_span, E0697, "closures cannot be static")
879 fn lower_expr_async_closure(
881 capture_clause: CaptureBy,
886 ) -> hir::ExprKind<'hir> {
888 FnDecl { inputs: decl.inputs.clone(), output: FnRetTy::Default(fn_decl_span) };
890 let body_id = self.with_new_scopes(|this| {
891 // FIXME(cramertj): allow `async` non-`move` closures with arguments.
892 if capture_clause == CaptureBy::Ref && !decl.inputs.is_empty() {
897 "`async` non-`move` closures with parameters are not currently supported",
900 "consider using `let` statements to manually capture \
901 variables by reference before entering an `async move` closure",
906 // Transform `async |x: u8| -> X { ... }` into
907 // `|x: u8| future_from_generator(|| -> X { ... })`.
908 let body_id = this.lower_fn_body(&outer_decl, |this| {
910 if let FnRetTy::Ty(ty) = &decl.output { Some(ty.clone()) } else { None };
911 let async_body = this.make_async_expr(
916 hir::AsyncGeneratorKind::Closure,
917 |this| this.with_new_scopes(|this| this.lower_expr_mut(body)),
919 this.expr(fn_decl_span, async_body, ThinVec::new())
924 // We need to lower the declaration outside the new scope, because we
925 // have to conserve the state of being inside a loop condition for the
926 // closure argument types.
927 let fn_decl = self.lower_fn_decl(&outer_decl, None, FnDeclKind::Closure, None);
929 hir::ExprKind::Closure(
933 self.lower_span(fn_decl_span),
938 /// Destructure the LHS of complex assignments.
939 /// For instance, lower `(a, b) = t` to `{ let (lhs1, lhs2) = t; a = lhs1; b = lhs2; }`.
940 fn lower_expr_assign(
946 ) -> hir::ExprKind<'hir> {
947 // Return early in case of an ordinary assignment.
948 fn is_ordinary(lower_ctx: &mut LoweringContext<'_, '_>, lhs: &Expr) -> bool {
951 | ExprKind::Struct(..)
953 | ExprKind::Underscore => false,
954 // Check for tuple struct constructor.
955 ExprKind::Call(callee, ..) => lower_ctx.extract_tuple_struct_path(callee).is_none(),
956 ExprKind::Paren(e) => {
958 // We special-case `(..)` for consistency with patterns.
959 ExprKind::Range(None, None, RangeLimits::HalfOpen) => false,
960 _ => is_ordinary(lower_ctx, e),
966 if is_ordinary(self, lhs) {
967 return hir::ExprKind::Assign(
968 self.lower_expr(lhs),
969 self.lower_expr(rhs),
970 self.lower_span(eq_sign_span),
974 let mut assignments = vec![];
976 // The LHS becomes a pattern: `(lhs1, lhs2)`.
977 let pat = self.destructure_assign(lhs, eq_sign_span, &mut assignments);
978 let rhs = self.lower_expr(rhs);
980 // Introduce a `let` for destructuring: `let (lhs1, lhs2) = t`.
981 let destructure_let = self.stmt_let_pat(
986 hir::LocalSource::AssignDesugar(self.lower_span(eq_sign_span)),
989 // `a = lhs1; b = lhs2;`.
992 .alloc_from_iter(std::iter::once(destructure_let).chain(assignments.into_iter()));
994 // Wrap everything in a block.
995 hir::ExprKind::Block(&self.block_all(whole_span, stmts, None), None)
998 /// If the given expression is a path to a tuple struct, returns that path.
999 /// It is not a complete check, but just tries to reject most paths early
1000 /// if they are not tuple structs.
1001 /// Type checking will take care of the full validation later.
1002 fn extract_tuple_struct_path<'a>(
1005 ) -> Option<(&'a Option<QSelf>, &'a Path)> {
1006 if let ExprKind::Path(qself, path) = &expr.kind {
1007 // Does the path resolve to something disallowed in a tuple struct/variant pattern?
1008 if let Some(partial_res) = self.resolver.get_partial_res(expr.id) {
1009 if partial_res.unresolved_segments() == 0
1010 && !partial_res.base_res().expected_in_tuple_struct_pat()
1015 return Some((qself, path));
1020 /// Convert the LHS of a destructuring assignment to a pattern.
1021 /// Each sub-assignment is recorded in `assignments`.
1022 fn destructure_assign(
1026 assignments: &mut Vec<hir::Stmt<'hir>>,
1027 ) -> &'hir hir::Pat<'hir> {
1028 self.arena.alloc(self.destructure_assign_mut(lhs, eq_sign_span, assignments))
1031 fn destructure_assign_mut(
1035 assignments: &mut Vec<hir::Stmt<'hir>>,
1036 ) -> hir::Pat<'hir> {
1038 // Underscore pattern.
1039 ExprKind::Underscore => {
1040 return self.pat_without_dbm(lhs.span, hir::PatKind::Wild);
1043 ExprKind::Array(elements) => {
1045 self.destructure_sequence(elements, "slice", eq_sign_span, assignments);
1046 let slice_pat = if let Some((i, span)) = rest {
1047 let (before, after) = pats.split_at(i);
1048 hir::PatKind::Slice(
1050 Some(self.arena.alloc(self.pat_without_dbm(span, hir::PatKind::Wild))),
1054 hir::PatKind::Slice(pats, None, &[])
1056 return self.pat_without_dbm(lhs.span, slice_pat);
1059 ExprKind::Call(callee, args) => {
1060 if let Some((qself, path)) = self.extract_tuple_struct_path(callee) {
1061 let (pats, rest) = self.destructure_sequence(
1063 "tuple struct or variant",
1067 let qpath = self.lower_qpath(
1071 ParamMode::Optional,
1072 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1074 // Destructure like a tuple struct.
1075 let tuple_struct_pat =
1076 hir::PatKind::TupleStruct(qpath, pats, rest.map(|r| r.0));
1077 return self.pat_without_dbm(lhs.span, tuple_struct_pat);
1081 ExprKind::Struct(se) => {
1082 let field_pats = self.arena.alloc_from_iter(se.fields.iter().map(|f| {
1083 let pat = self.destructure_assign(&f.expr, eq_sign_span, assignments);
1085 hir_id: self.next_id(),
1086 ident: self.lower_ident(f.ident),
1088 is_shorthand: f.is_shorthand,
1089 span: self.lower_span(f.span),
1092 let qpath = self.lower_qpath(
1096 ParamMode::Optional,
1097 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1099 let fields_omitted = match &se.rest {
1100 StructRest::Base(e) => {
1104 "functional record updates are not allowed in destructuring \
1109 "consider removing the trailing pattern",
1111 rustc_errors::Applicability::MachineApplicable,
1116 StructRest::Rest(_) => true,
1117 StructRest::None => false,
1119 let struct_pat = hir::PatKind::Struct(qpath, field_pats, fields_omitted);
1120 return self.pat_without_dbm(lhs.span, struct_pat);
1123 ExprKind::Tup(elements) => {
1125 self.destructure_sequence(elements, "tuple", eq_sign_span, assignments);
1126 let tuple_pat = hir::PatKind::Tuple(pats, rest.map(|r| r.0));
1127 return self.pat_without_dbm(lhs.span, tuple_pat);
1129 ExprKind::Paren(e) => {
1130 // We special-case `(..)` for consistency with patterns.
1131 if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
1132 let tuple_pat = hir::PatKind::Tuple(&[], Some(0));
1133 return self.pat_without_dbm(lhs.span, tuple_pat);
1135 return self.destructure_assign_mut(e, eq_sign_span, assignments);
1140 // Treat all other cases as normal lvalue.
1141 let ident = Ident::new(sym::lhs, self.lower_span(lhs.span));
1142 let (pat, binding) = self.pat_ident_mut(lhs.span, ident);
1143 let ident = self.expr_ident(lhs.span, ident, binding);
1145 hir::ExprKind::Assign(self.lower_expr(lhs), ident, self.lower_span(eq_sign_span));
1146 let expr = self.expr(lhs.span, assign, ThinVec::new());
1147 assignments.push(self.stmt_expr(lhs.span, expr));
1151 /// Destructure a sequence of expressions occurring on the LHS of an assignment.
1152 /// Such a sequence occurs in a tuple (struct)/slice.
1153 /// Return a sequence of corresponding patterns, and the index and the span of `..` if it
1155 /// Each sub-assignment is recorded in `assignments`.
1156 fn destructure_sequence(
1158 elements: &[AstP<Expr>],
1161 assignments: &mut Vec<hir::Stmt<'hir>>,
1162 ) -> (&'hir [hir::Pat<'hir>], Option<(usize, Span)>) {
1163 let mut rest = None;
1165 self.arena.alloc_from_iter(elements.iter().enumerate().filter_map(|(i, e)| {
1166 // Check for `..` pattern.
1167 if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
1168 if let Some((_, prev_span)) = rest {
1169 self.ban_extra_rest_pat(e.span, prev_span, ctx);
1171 rest = Some((i, e.span));
1175 Some(self.destructure_assign_mut(e, eq_sign_span, assignments))
1181 /// Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`.
1182 fn lower_expr_range_closed(&mut self, span: Span, e1: &Expr, e2: &Expr) -> hir::ExprKind<'hir> {
1183 let e1 = self.lower_expr_mut(e1);
1184 let e2 = self.lower_expr_mut(e2);
1186 hir::QPath::LangItem(hir::LangItem::RangeInclusiveNew, self.lower_span(span), None);
1188 self.arena.alloc(self.expr(span, hir::ExprKind::Path(fn_path), ThinVec::new()));
1189 hir::ExprKind::Call(fn_expr, arena_vec![self; e1, e2])
1192 fn lower_expr_range(
1198 ) -> hir::ExprKind<'hir> {
1199 use rustc_ast::RangeLimits::*;
1201 let lang_item = match (e1, e2, lims) {
1202 (None, None, HalfOpen) => hir::LangItem::RangeFull,
1203 (Some(..), None, HalfOpen) => hir::LangItem::RangeFrom,
1204 (None, Some(..), HalfOpen) => hir::LangItem::RangeTo,
1205 (Some(..), Some(..), HalfOpen) => hir::LangItem::Range,
1206 (None, Some(..), Closed) => hir::LangItem::RangeToInclusive,
1207 (Some(..), Some(..), Closed) => unreachable!(),
1208 (_, None, Closed) => self.diagnostic().span_fatal(span, "inclusive range with no end"),
1211 let fields = self.arena.alloc_from_iter(
1212 e1.iter().map(|e| (sym::start, e)).chain(e2.iter().map(|e| (sym::end, e))).map(
1214 let expr = self.lower_expr(&e);
1215 let ident = Ident::new(s, self.lower_span(e.span));
1216 self.expr_field(ident, expr, e.span)
1221 hir::ExprKind::Struct(
1222 self.arena.alloc(hir::QPath::LangItem(lang_item, self.lower_span(span), None)),
1228 fn lower_label(&self, opt_label: Option<Label>) -> Option<Label> {
1229 let label = opt_label?;
1230 Some(Label { ident: self.lower_ident(label.ident) })
1233 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
1234 let target_id = match destination {
1236 if let Some(loop_id) = self.resolver.get_label_res(id) {
1237 Ok(self.lower_node_id(loop_id))
1239 Err(hir::LoopIdError::UnresolvedLabel)
1244 .map(|id| Ok(self.lower_node_id(id)))
1245 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope)),
1247 let label = self.lower_label(destination.map(|(_, label)| label));
1248 hir::Destination { label, target_id }
1251 fn lower_jump_destination(&mut self, id: NodeId, opt_label: Option<Label>) -> hir::Destination {
1252 if self.is_in_loop_condition && opt_label.is_none() {
1255 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition),
1258 self.lower_loop_destination(opt_label.map(|label| (id, label)))
1262 fn with_catch_scope<T>(&mut self, catch_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1263 let old_scope = self.catch_scope.replace(catch_id);
1264 let result = f(self);
1265 self.catch_scope = old_scope;
1269 fn with_loop_scope<T>(&mut self, loop_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1270 // We're no longer in the base loop's condition; we're in another loop.
1271 let was_in_loop_condition = self.is_in_loop_condition;
1272 self.is_in_loop_condition = false;
1274 let old_scope = self.loop_scope.replace(loop_id);
1275 let result = f(self);
1276 self.loop_scope = old_scope;
1278 self.is_in_loop_condition = was_in_loop_condition;
1283 fn with_loop_condition_scope<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
1284 let was_in_loop_condition = self.is_in_loop_condition;
1285 self.is_in_loop_condition = true;
1287 let result = f(self);
1289 self.is_in_loop_condition = was_in_loop_condition;
1294 fn lower_expr_field(&mut self, f: &ExprField) -> hir::ExprField<'hir> {
1296 hir_id: self.next_id(),
1297 ident: self.lower_ident(f.ident),
1298 expr: self.lower_expr(&f.expr),
1299 span: self.lower_span(f.span),
1300 is_shorthand: f.is_shorthand,
1304 fn lower_expr_yield(&mut self, span: Span, opt_expr: Option<&Expr>) -> hir::ExprKind<'hir> {
1305 match self.generator_kind {
1306 Some(hir::GeneratorKind::Gen) => {}
1307 Some(hir::GeneratorKind::Async(_)) => {
1312 "`async` generators are not yet supported"
1316 None => self.generator_kind = Some(hir::GeneratorKind::Gen),
1320 opt_expr.as_ref().map(|x| self.lower_expr(x)).unwrap_or_else(|| self.expr_unit(span));
1322 hir::ExprKind::Yield(expr, hir::YieldSource::Yield)
1325 /// Desugar `ExprForLoop` from: `[opt_ident]: for <pat> in <head> <body>` into:
1328 /// let result = match IntoIterator::into_iter(<head>) {
1330 /// [opt_ident]: loop {
1331 /// match Iterator::next(&mut iter) {
1333 /// Some(<pat>) => <body>,
1347 opt_label: Option<Label>,
1348 ) -> hir::Expr<'hir> {
1349 let head = self.lower_expr_mut(head);
1350 let pat = self.lower_pat(pat);
1352 self.mark_span_with_reason(DesugaringKind::ForLoop, self.lower_span(e.span), None);
1353 let head_span = self.mark_span_with_reason(DesugaringKind::ForLoop, head.span, None);
1354 let pat_span = self.mark_span_with_reason(DesugaringKind::ForLoop, pat.span, None);
1359 self.with_loop_scope(e.id, |this| this.expr_break_alloc(for_span, ThinVec::new()));
1360 let pat = self.pat_none(for_span);
1361 self.arm(pat, break_expr)
1364 // Some(<pat>) => <body>,
1366 let some_pat = self.pat_some(pat_span, pat);
1367 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
1368 let body_expr = self.arena.alloc(self.expr_block(body_block, ThinVec::new()));
1369 self.arm(some_pat, body_expr)
1373 let iter = Ident::with_dummy_span(sym::iter);
1374 let (iter_pat, iter_pat_nid) =
1375 self.pat_ident_binding_mode(head_span, iter, hir::BindingAnnotation::Mutable);
1377 // `match Iterator::next(&mut iter) { ... }`
1379 let iter = self.expr_ident(head_span, iter, iter_pat_nid);
1380 let ref_mut_iter = self.expr_mut_addr_of(head_span, iter);
1381 let next_expr = self.expr_call_lang_item_fn(
1383 hir::LangItem::IteratorNext,
1384 arena_vec![self; ref_mut_iter],
1387 let arms = arena_vec![self; none_arm, some_arm];
1389 self.expr_match(head_span, next_expr, arms, hir::MatchSource::ForLoopDesugar)
1391 let match_stmt = self.stmt_expr(for_span, match_expr);
1393 let loop_block = self.block_all(for_span, arena_vec![self; match_stmt], None);
1395 // `[opt_ident]: loop { ... }`
1396 let kind = hir::ExprKind::Loop(
1398 self.lower_label(opt_label),
1399 hir::LoopSource::ForLoop,
1400 self.lower_span(for_span.with_hi(head.span.hi())),
1403 self.arena.alloc(hir::Expr { hir_id: self.lower_node_id(e.id), kind, span: for_span });
1405 // `mut iter => { ... }`
1406 let iter_arm = self.arm(iter_pat, loop_expr);
1408 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
1409 let into_iter_expr = {
1410 self.expr_call_lang_item_fn(
1412 hir::LangItem::IntoIterIntoIter,
1413 arena_vec![self; head],
1418 let match_expr = self.arena.alloc(self.expr_match(
1421 arena_vec![self; iter_arm],
1422 hir::MatchSource::ForLoopDesugar,
1425 let attrs: Vec<_> = e.attrs.iter().map(|a| self.lower_attr(a)).collect();
1427 // This is effectively `{ let _result = ...; _result }`.
1428 // The construct was introduced in #21984 and is necessary to make sure that
1429 // temporaries in the `head` expression are dropped and do not leak to the
1430 // surrounding scope of the `match` since the `match` is not a terminating scope.
1432 // Also, add the attributes to the outer returned expr node.
1433 self.expr_drop_temps_mut(for_span, match_expr, attrs.into())
1436 /// Desugar `ExprKind::Try` from: `<expr>?` into:
1438 /// match Try::branch(<expr>) {
1439 /// ControlFlow::Continue(val) => #[allow(unreachable_code)] val,,
1440 /// ControlFlow::Break(residual) =>
1441 /// #[allow(unreachable_code)]
1442 /// // If there is an enclosing `try {...}`:
1443 /// break 'catch_target Try::from_residual(residual),
1445 /// return Try::from_residual(residual),
1448 fn lower_expr_try(&mut self, span: Span, sub_expr: &Expr) -> hir::ExprKind<'hir> {
1449 let unstable_span = self.mark_span_with_reason(
1450 DesugaringKind::QuestionMark,
1452 self.allow_try_trait.clone(),
1454 let try_span = self.sess.source_map().end_point(span);
1455 let try_span = self.mark_span_with_reason(
1456 DesugaringKind::QuestionMark,
1458 self.allow_try_trait.clone(),
1461 // `Try::branch(<expr>)`
1464 let sub_expr = self.lower_expr_mut(sub_expr);
1466 self.expr_call_lang_item_fn(
1468 hir::LangItem::TryTraitBranch,
1469 arena_vec![self; sub_expr],
1474 // `#[allow(unreachable_code)]`
1476 // `allow(unreachable_code)`
1478 let allow_ident = Ident::new(sym::allow, self.lower_span(span));
1479 let uc_ident = Ident::new(sym::unreachable_code, self.lower_span(span));
1480 let uc_nested = attr::mk_nested_word_item(uc_ident);
1481 attr::mk_list_item(allow_ident, vec![uc_nested])
1483 attr::mk_attr_outer(allow)
1485 let attrs = vec![attr];
1487 // `ControlFlow::Continue(val) => #[allow(unreachable_code)] val,`
1488 let continue_arm = {
1489 let val_ident = Ident::with_dummy_span(sym::val);
1490 let (val_pat, val_pat_nid) = self.pat_ident(span, val_ident);
1491 let val_expr = self.arena.alloc(self.expr_ident_with_attrs(
1495 ThinVec::from(attrs.clone()),
1497 let continue_pat = self.pat_cf_continue(unstable_span, val_pat);
1498 self.arm(continue_pat, val_expr)
1501 // `ControlFlow::Break(residual) =>
1502 // #[allow(unreachable_code)]
1503 // return Try::from_residual(residual),`
1505 let residual_ident = Ident::with_dummy_span(sym::residual);
1506 let (residual_local, residual_local_nid) = self.pat_ident(try_span, residual_ident);
1507 let residual_expr = self.expr_ident_mut(try_span, residual_ident, residual_local_nid);
1508 let from_residual_expr = self.wrap_in_try_constructor(
1509 hir::LangItem::TryTraitFromResidual,
1511 self.arena.alloc(residual_expr),
1514 let thin_attrs = ThinVec::from(attrs);
1515 let ret_expr = if let Some(catch_node) = self.catch_scope {
1516 let target_id = Ok(self.lower_node_id(catch_node));
1517 self.arena.alloc(self.expr(
1519 hir::ExprKind::Break(
1520 hir::Destination { label: None, target_id },
1521 Some(from_residual_expr),
1526 self.arena.alloc(self.expr(
1528 hir::ExprKind::Ret(Some(from_residual_expr)),
1533 let break_pat = self.pat_cf_break(try_span, residual_local);
1534 self.arm(break_pat, ret_expr)
1537 hir::ExprKind::Match(
1539 arena_vec![self; break_arm, continue_arm],
1540 hir::MatchSource::TryDesugar,
1544 // =========================================================================
1545 // Helper methods for building HIR.
1546 // =========================================================================
1548 /// Wrap the given `expr` in a terminating scope using `hir::ExprKind::DropTemps`.
1550 /// In terms of drop order, it has the same effect as wrapping `expr` in
1551 /// `{ let _t = $expr; _t }` but should provide better compile-time performance.
1553 /// The drop order can be important in e.g. `if expr { .. }`.
1554 pub(super) fn expr_drop_temps(
1557 expr: &'hir hir::Expr<'hir>,
1559 ) -> &'hir hir::Expr<'hir> {
1560 self.arena.alloc(self.expr_drop_temps_mut(span, expr, attrs))
1563 pub(super) fn expr_drop_temps_mut(
1566 expr: &'hir hir::Expr<'hir>,
1568 ) -> hir::Expr<'hir> {
1569 self.expr(span, hir::ExprKind::DropTemps(expr), attrs)
1575 arg: &'hir hir::Expr<'hir>,
1576 arms: &'hir [hir::Arm<'hir>],
1577 source: hir::MatchSource,
1578 ) -> hir::Expr<'hir> {
1579 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
1582 fn expr_break(&mut self, span: Span, attrs: AttrVec) -> hir::Expr<'hir> {
1583 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
1584 self.expr(span, expr_break, attrs)
1587 fn expr_break_alloc(&mut self, span: Span, attrs: AttrVec) -> &'hir hir::Expr<'hir> {
1588 let expr_break = self.expr_break(span, attrs);
1589 self.arena.alloc(expr_break)
1592 fn expr_mut_addr_of(&mut self, span: Span, e: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
1595 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Mut, e),
1600 fn expr_unit(&mut self, sp: Span) -> &'hir hir::Expr<'hir> {
1601 self.arena.alloc(self.expr(sp, hir::ExprKind::Tup(&[]), ThinVec::new()))
1607 e: &'hir hir::Expr<'hir>,
1608 args: &'hir [hir::Expr<'hir>],
1609 ) -> hir::Expr<'hir> {
1610 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
1616 e: &'hir hir::Expr<'hir>,
1617 args: &'hir [hir::Expr<'hir>],
1618 ) -> &'hir hir::Expr<'hir> {
1619 self.arena.alloc(self.expr_call_mut(span, e, args))
1622 fn expr_call_lang_item_fn_mut(
1625 lang_item: hir::LangItem,
1626 args: &'hir [hir::Expr<'hir>],
1627 hir_id: Option<hir::HirId>,
1628 ) -> hir::Expr<'hir> {
1630 self.arena.alloc(self.expr_lang_item_path(span, lang_item, ThinVec::new(), hir_id));
1631 self.expr_call_mut(span, path, args)
1634 fn expr_call_lang_item_fn(
1637 lang_item: hir::LangItem,
1638 args: &'hir [hir::Expr<'hir>],
1639 hir_id: Option<hir::HirId>,
1640 ) -> &'hir hir::Expr<'hir> {
1641 self.arena.alloc(self.expr_call_lang_item_fn_mut(span, lang_item, args, hir_id))
1644 fn expr_lang_item_path(
1647 lang_item: hir::LangItem,
1649 hir_id: Option<hir::HirId>,
1650 ) -> hir::Expr<'hir> {
1653 hir::ExprKind::Path(hir::QPath::LangItem(lang_item, self.lower_span(span), hir_id)),
1658 pub(super) fn expr_ident(
1662 binding: hir::HirId,
1663 ) -> &'hir hir::Expr<'hir> {
1664 self.arena.alloc(self.expr_ident_mut(sp, ident, binding))
1667 pub(super) fn expr_ident_mut(
1671 binding: hir::HirId,
1672 ) -> hir::Expr<'hir> {
1673 self.expr_ident_with_attrs(sp, ident, binding, ThinVec::new())
1676 fn expr_ident_with_attrs(
1680 binding: hir::HirId,
1682 ) -> hir::Expr<'hir> {
1683 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
1685 self.arena.alloc(hir::Path {
1686 span: self.lower_span(span),
1687 res: Res::Local(binding),
1688 segments: arena_vec![self; hir::PathSegment::from_ident(ident)],
1692 self.expr(span, expr_path, attrs)
1695 fn expr_unsafe(&mut self, expr: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
1696 let hir_id = self.next_id();
1697 let span = expr.span;
1700 hir::ExprKind::Block(
1701 self.arena.alloc(hir::Block {
1705 rules: hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::CompilerGenerated),
1706 span: self.lower_span(span),
1707 targeted_by_break: false,
1715 fn expr_block_empty(&mut self, span: Span) -> &'hir hir::Expr<'hir> {
1716 let blk = self.block_all(span, &[], None);
1717 let expr = self.expr_block(blk, ThinVec::new());
1718 self.arena.alloc(expr)
1721 pub(super) fn expr_block(
1723 b: &'hir hir::Block<'hir>,
1725 ) -> hir::Expr<'hir> {
1726 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
1732 kind: hir::ExprKind<'hir>,
1734 ) -> hir::Expr<'hir> {
1735 let hir_id = self.next_id();
1736 self.lower_attrs(hir_id, &attrs);
1737 hir::Expr { hir_id, kind, span: self.lower_span(span) }
1743 expr: &'hir hir::Expr<'hir>,
1745 ) -> hir::ExprField<'hir> {
1747 hir_id: self.next_id(),
1749 span: self.lower_span(span),
1751 is_shorthand: false,
1755 fn arm(&mut self, pat: &'hir hir::Pat<'hir>, expr: &'hir hir::Expr<'hir>) -> hir::Arm<'hir> {
1757 hir_id: self.next_id(),
1760 span: self.lower_span(expr.span),