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(
56 ParenthesizedGenericArgs::Err,
57 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
59 let args = self.lower_exprs(args);
60 hir::ExprKind::MethodCall(hir_seg, args, self.lower_span(span))
62 ExprKind::Binary(binop, ref lhs, ref rhs) => {
63 let binop = self.lower_binop(binop);
64 let lhs = self.lower_expr(lhs);
65 let rhs = self.lower_expr(rhs);
66 hir::ExprKind::Binary(binop, lhs, rhs)
68 ExprKind::Unary(op, ref ohs) => {
69 let op = self.lower_unop(op);
70 let ohs = self.lower_expr(ohs);
71 hir::ExprKind::Unary(op, ohs)
73 ExprKind::Lit(ref l) => {
74 hir::ExprKind::Lit(respan(self.lower_span(l.span), l.kind.clone()))
76 ExprKind::Cast(ref expr, ref ty) => {
77 let expr = self.lower_expr(expr);
79 self.lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type));
80 hir::ExprKind::Cast(expr, ty)
82 ExprKind::Type(ref expr, ref ty) => {
83 let expr = self.lower_expr(expr);
85 self.lower_ty(ty, ImplTraitContext::Disallowed(ImplTraitPosition::Type));
86 hir::ExprKind::Type(expr, ty)
88 ExprKind::AddrOf(k, m, ref ohs) => {
89 let ohs = self.lower_expr(ohs);
90 hir::ExprKind::AddrOf(k, m, ohs)
92 ExprKind::Let(ref pat, ref scrutinee, span) => {
93 hir::ExprKind::Let(self.arena.alloc(hir::Let {
94 hir_id: self.next_id(),
95 span: self.lower_span(span),
96 pat: self.lower_pat(pat),
98 init: self.lower_expr(scrutinee),
101 ExprKind::If(ref cond, ref then, ref else_opt) => {
102 self.lower_expr_if(cond, then, else_opt.as_deref())
104 ExprKind::While(ref cond, ref body, opt_label) => {
105 self.with_loop_scope(e.id, |this| {
107 this.mark_span_with_reason(DesugaringKind::WhileLoop, e.span, None);
108 this.lower_expr_while_in_loop_scope(span, cond, body, opt_label)
111 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
113 this.lower_block(body, false),
114 this.lower_label(opt_label),
115 hir::LoopSource::Loop,
119 ExprKind::TryBlock(ref body) => self.lower_expr_try_block(body),
120 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
121 self.lower_expr(expr),
122 self.arena.alloc_from_iter(arms.iter().map(|x| self.lower_arm(x))),
123 hir::MatchSource::Normal,
125 ExprKind::Async(capture_clause, closure_node_id, ref block) => self
131 hir::AsyncGeneratorKind::Block,
132 |this| this.with_new_scopes(|this| this.lower_block_expr(block)),
134 ExprKind::Await(ref expr) => {
135 let span = if expr.span.hi() < e.span.hi() {
136 expr.span.shrink_to_hi().with_hi(e.span.hi())
138 // this is a recovered `await expr`
141 self.lower_expr_await(span, expr)
151 if let Async::Yes { closure_id, .. } = asyncness {
152 self.lower_expr_async_closure(
160 self.lower_expr_closure(
169 ExprKind::Block(ref blk, opt_label) => {
170 let opt_label = self.lower_label(opt_label);
171 hir::ExprKind::Block(self.lower_block(blk, opt_label.is_some()), opt_label)
173 ExprKind::Assign(ref el, ref er, span) => {
174 self.lower_expr_assign(el, er, span, e.span)
176 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
177 self.lower_binop(op),
181 ExprKind::Field(ref el, ident) => {
182 hir::ExprKind::Field(self.lower_expr(el), self.lower_ident(ident))
184 ExprKind::Index(ref el, ref er) => {
185 hir::ExprKind::Index(self.lower_expr(el), self.lower_expr(er))
187 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
188 self.lower_expr_range_closed(e.span, e1, e2)
190 ExprKind::Range(ref e1, ref e2, lims) => {
191 self.lower_expr_range(e.span, e1.as_deref(), e2.as_deref(), lims)
193 ExprKind::Underscore => {
197 "in expressions, `_` can only be used on the left-hand side of an assignment",
199 .span_label(e.span, "`_` not allowed here")
203 ExprKind::Path(ref qself, ref path) => {
204 let qpath = self.lower_qpath(
209 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
211 hir::ExprKind::Path(qpath)
213 ExprKind::Break(opt_label, ref opt_expr) => {
214 let opt_expr = opt_expr.as_ref().map(|x| self.lower_expr(x));
215 hir::ExprKind::Break(self.lower_jump_destination(e.id, opt_label), opt_expr)
217 ExprKind::Continue(opt_label) => {
218 hir::ExprKind::Continue(self.lower_jump_destination(e.id, opt_label))
220 ExprKind::Ret(ref e) => {
221 let e = e.as_ref().map(|x| self.lower_expr(x));
222 hir::ExprKind::Ret(e)
224 ExprKind::InlineAsm(ref asm) => {
225 hir::ExprKind::InlineAsm(self.lower_inline_asm(e.span, asm))
227 ExprKind::Struct(ref se) => {
228 let rest = match &se.rest {
229 StructRest::Base(e) => Some(self.lower_expr(e)),
230 StructRest::Rest(sp) => {
232 .struct_span_err(*sp, "base expression required after `..`")
233 .span_label(*sp, "add a base expression here")
235 Some(&*self.arena.alloc(self.expr_err(*sp)))
237 StructRest::None => None,
239 hir::ExprKind::Struct(
240 self.arena.alloc(self.lower_qpath(
245 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
248 .alloc_from_iter(se.fields.iter().map(|x| self.lower_expr_field(x))),
252 ExprKind::Yield(ref opt_expr) => self.lower_expr_yield(e.span, opt_expr.as_deref()),
253 ExprKind::Err => hir::ExprKind::Err,
254 ExprKind::Try(ref sub_expr) => self.lower_expr_try(e.span, sub_expr),
255 ExprKind::Paren(ref ex) => {
256 let mut ex = self.lower_expr_mut(ex);
257 // Include parens in span, but only if it is a super-span.
258 if e.span.contains(ex.span) {
259 ex.span = self.lower_span(e.span);
261 // Merge attributes into the inner expression.
262 if !e.attrs.is_empty() {
264 self.attrs.get(&ex.hir_id.local_id).map(|la| *la).unwrap_or(&[]);
267 &*self.arena.alloc_from_iter(
270 .map(|a| self.lower_attr(a))
271 .chain(old_attrs.iter().cloned()),
278 // Desugar `ExprForLoop`
279 // from: `[opt_ident]: for <pat> in <head> <body>`
280 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
281 return self.lower_expr_for(e, pat, head, body, opt_label);
283 ExprKind::MacCall(_) => panic!("{:?} shouldn't exist here", e.span),
286 let hir_id = self.lower_node_id(e.id);
287 self.lower_attrs(hir_id, &e.attrs);
288 hir::Expr { hir_id, kind, span: self.lower_span(e.span) }
292 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
294 UnOp::Deref => hir::UnOp::Deref,
295 UnOp::Not => hir::UnOp::Not,
296 UnOp::Neg => hir::UnOp::Neg,
300 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
303 BinOpKind::Add => hir::BinOpKind::Add,
304 BinOpKind::Sub => hir::BinOpKind::Sub,
305 BinOpKind::Mul => hir::BinOpKind::Mul,
306 BinOpKind::Div => hir::BinOpKind::Div,
307 BinOpKind::Rem => hir::BinOpKind::Rem,
308 BinOpKind::And => hir::BinOpKind::And,
309 BinOpKind::Or => hir::BinOpKind::Or,
310 BinOpKind::BitXor => hir::BinOpKind::BitXor,
311 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
312 BinOpKind::BitOr => hir::BinOpKind::BitOr,
313 BinOpKind::Shl => hir::BinOpKind::Shl,
314 BinOpKind::Shr => hir::BinOpKind::Shr,
315 BinOpKind::Eq => hir::BinOpKind::Eq,
316 BinOpKind::Lt => hir::BinOpKind::Lt,
317 BinOpKind::Le => hir::BinOpKind::Le,
318 BinOpKind::Ne => hir::BinOpKind::Ne,
319 BinOpKind::Ge => hir::BinOpKind::Ge,
320 BinOpKind::Gt => hir::BinOpKind::Gt,
322 span: self.lower_span(b.span),
326 fn lower_legacy_const_generics(
329 args: Vec<AstP<Expr>>,
330 legacy_args_idx: &[usize],
331 ) -> hir::ExprKind<'hir> {
332 let ExprKind::Path(None, ref mut path) = f.kind else {
336 // Split the arguments into const generics and normal arguments
337 let mut real_args = vec![];
338 let mut generic_args = vec![];
339 for (idx, arg) in args.into_iter().enumerate() {
340 if legacy_args_idx.contains(&idx) {
341 let parent_def_id = self.current_hir_id_owner;
342 let node_id = self.resolver.next_node_id();
344 // Add a definition for the in-band const def.
345 self.resolver.create_def(
348 DefPathData::AnonConst,
353 let anon_const = AnonConst { id: node_id, value: arg };
354 generic_args.push(AngleBracketedArg::Arg(GenericArg::Const(anon_const)));
360 // Add generic args to the last element of the path.
361 let last_segment = path.segments.last_mut().unwrap();
362 assert!(last_segment.args.is_none());
363 last_segment.args = Some(AstP(GenericArgs::AngleBracketed(AngleBracketedArgs {
368 // Now lower everything as normal.
369 let f = self.lower_expr(&f);
370 hir::ExprKind::Call(f, self.lower_exprs(&real_args))
377 else_opt: Option<&Expr>,
378 ) -> hir::ExprKind<'hir> {
379 let lowered_cond = self.lower_expr(cond);
380 let new_cond = self.manage_let_cond(lowered_cond);
381 let then_expr = self.lower_block_expr(then);
382 if let Some(rslt) = else_opt {
383 hir::ExprKind::If(new_cond, self.arena.alloc(then_expr), Some(self.lower_expr(rslt)))
385 hir::ExprKind::If(new_cond, self.arena.alloc(then_expr), None)
389 // If `cond` kind is `let`, returns `let`. Otherwise, wraps and returns `cond`
390 // in a temporary block.
391 fn manage_let_cond(&mut self, cond: &'hir hir::Expr<'hir>) -> &'hir hir::Expr<'hir> {
392 fn has_let_expr<'hir>(expr: &'hir hir::Expr<'hir>) -> bool {
394 hir::ExprKind::Binary(_, lhs, rhs) => has_let_expr(lhs) || has_let_expr(rhs),
395 hir::ExprKind::Let(..) => true,
399 if has_let_expr(cond) {
402 let reason = DesugaringKind::CondTemporary;
403 let span_block = self.mark_span_with_reason(reason, cond.span, None);
404 self.expr_drop_temps(span_block, cond, AttrVec::new())
408 // We desugar: `'label: while $cond $body` into:
412 // if { let _t = $cond; _t } {
421 // Wrap in a construct equivalent to `{ let _t = $cond; _t }`
422 // to preserve drop semantics since `while $cond { ... }` does not
423 // let temporaries live outside of `cond`.
424 fn lower_expr_while_in_loop_scope(
429 opt_label: Option<Label>,
430 ) -> hir::ExprKind<'hir> {
431 let lowered_cond = self.with_loop_condition_scope(|t| t.lower_expr(cond));
432 let new_cond = self.manage_let_cond(lowered_cond);
433 let then = self.lower_block_expr(body);
434 let expr_break = self.expr_break(span, ThinVec::new());
435 let stmt_break = self.stmt_expr(span, expr_break);
436 let else_blk = self.block_all(span, arena_vec![self; stmt_break], None);
437 let else_expr = self.arena.alloc(self.expr_block(else_blk, ThinVec::new()));
438 let if_kind = hir::ExprKind::If(new_cond, self.arena.alloc(then), Some(else_expr));
439 let if_expr = self.expr(span, if_kind, ThinVec::new());
440 let block = self.block_expr(self.arena.alloc(if_expr));
441 let span = self.lower_span(span.with_hi(cond.span.hi()));
442 let opt_label = self.lower_label(opt_label);
443 hir::ExprKind::Loop(block, opt_label, hir::LoopSource::While, span)
446 /// Desugar `try { <stmts>; <expr> }` into `{ <stmts>; ::std::ops::Try::from_output(<expr>) }`,
447 /// `try { <stmts>; }` into `{ <stmts>; ::std::ops::Try::from_output(()) }`
448 /// and save the block id to use it as a break target for desugaring of the `?` operator.
449 fn lower_expr_try_block(&mut self, body: &Block) -> hir::ExprKind<'hir> {
450 self.with_catch_scope(body.id, |this| {
451 let mut block = this.lower_block_noalloc(body, true);
453 // Final expression of the block (if present) or `()` with span at the end of block
454 let (try_span, tail_expr) = if let Some(expr) = block.expr.take() {
456 this.mark_span_with_reason(
457 DesugaringKind::TryBlock,
459 this.allow_try_trait.clone(),
464 let try_span = this.mark_span_with_reason(
465 DesugaringKind::TryBlock,
466 this.sess.source_map().end_point(body.span),
467 this.allow_try_trait.clone(),
470 (try_span, this.expr_unit(try_span))
473 let ok_wrapped_span =
474 this.mark_span_with_reason(DesugaringKind::TryBlock, tail_expr.span, None);
476 // `::std::ops::Try::from_output($tail_expr)`
477 block.expr = Some(this.wrap_in_try_constructor(
478 hir::LangItem::TryTraitFromOutput,
484 hir::ExprKind::Block(this.arena.alloc(block), None)
488 fn wrap_in_try_constructor(
490 lang_item: hir::LangItem,
492 expr: &'hir hir::Expr<'hir>,
494 ) -> &'hir hir::Expr<'hir> {
495 let constructor = self.arena.alloc(self.expr_lang_item_path(
501 self.expr_call(overall_span, constructor, std::slice::from_ref(expr))
504 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm<'hir> {
505 let pat = self.lower_pat(&arm.pat);
506 let guard = arm.guard.as_ref().map(|cond| {
507 if let ExprKind::Let(ref pat, ref scrutinee, _) = cond.kind {
508 hir::Guard::IfLet(self.lower_pat(pat), self.lower_expr(scrutinee))
510 hir::Guard::If(self.lower_expr(cond))
513 let hir_id = self.next_id();
514 self.lower_attrs(hir_id, &arm.attrs);
519 body: self.lower_expr(&arm.body),
520 span: self.lower_span(arm.span),
524 /// Lower an `async` construct to a generator that is then wrapped so it implements `Future`.
529 /// std::future::from_generator(static move? |_task_context| -> <ret_ty> {
533 pub(super) fn make_async_expr(
535 capture_clause: CaptureBy,
536 closure_node_id: NodeId,
537 ret_ty: Option<AstP<Ty>>,
539 async_gen_kind: hir::AsyncGeneratorKind,
540 body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
541 ) -> hir::ExprKind<'hir> {
542 let output = match ret_ty {
543 Some(ty) => hir::FnRetTy::Return(
544 self.lower_ty(&ty, ImplTraitContext::Disallowed(ImplTraitPosition::AsyncBlock)),
546 None => hir::FnRetTy::DefaultReturn(self.lower_span(span)),
549 // Resume argument type. We let the compiler infer this to simplify the lowering. It is
550 // fully constrained by `future::from_generator`.
551 let input_ty = hir::Ty {
552 hir_id: self.next_id(),
553 kind: hir::TyKind::Infer,
554 span: self.lower_span(span),
557 // The closure/generator `FnDecl` takes a single (resume) argument of type `input_ty`.
558 let decl = self.arena.alloc(hir::FnDecl {
559 inputs: arena_vec![self; input_ty],
562 implicit_self: hir::ImplicitSelfKind::None,
565 // Lower the argument pattern/ident. The ident is used again in the `.await` lowering.
566 let (pat, task_context_hid) = self.pat_ident_binding_mode(
568 Ident::with_dummy_span(sym::_task_context),
569 hir::BindingAnnotation::Mutable,
571 let param = hir::Param {
572 hir_id: self.next_id(),
574 ty_span: self.lower_span(span),
575 span: self.lower_span(span),
577 let params = arena_vec![self; param];
579 let body_id = self.lower_body(move |this| {
580 this.generator_kind = Some(hir::GeneratorKind::Async(async_gen_kind));
582 let old_ctx = this.task_context;
583 this.task_context = Some(task_context_hid);
584 let res = body(this);
585 this.task_context = old_ctx;
589 // `static |_task_context| -> <ret_ty> { body }`:
590 let generator_kind = hir::ExprKind::Closure(
594 self.lower_span(span),
595 Some(hir::Movability::Static),
597 let generator = hir::Expr {
598 hir_id: self.lower_node_id(closure_node_id),
599 kind: generator_kind,
600 span: self.lower_span(span),
603 // `future::from_generator`:
605 self.mark_span_with_reason(DesugaringKind::Async, span, self.allow_gen_future.clone());
606 let gen_future = self.expr_lang_item_path(
608 hir::LangItem::FromGenerator,
613 // `future::from_generator(generator)`:
614 hir::ExprKind::Call(self.arena.alloc(gen_future), arena_vec![self; generator])
617 /// Desugar `<expr>.await` into:
618 /// ```ignore (pseudo-rust)
619 /// match ::std::future::IntoFuture::into_future(<expr>) {
620 /// mut __awaitee => loop {
621 /// match unsafe { ::std::future::Future::poll(
622 /// <::std::pin::Pin>::new_unchecked(&mut __awaitee),
623 /// ::std::future::get_context(task_context),
625 /// ::std::task::Poll::Ready(result) => break result,
626 /// ::std::task::Poll::Pending => {}
628 /// task_context = yield ();
632 fn lower_expr_await(&mut self, dot_await_span: Span, expr: &Expr) -> hir::ExprKind<'hir> {
633 let full_span = expr.span.to(dot_await_span);
634 match self.generator_kind {
635 Some(hir::GeneratorKind::Async(_)) => {}
636 Some(hir::GeneratorKind::Gen) | None => {
637 let mut err = struct_span_err!(
641 "`await` is only allowed inside `async` functions and blocks"
643 err.span_label(dot_await_span, "only allowed inside `async` functions and blocks");
644 if let Some(item_sp) = self.current_item {
645 err.span_label(item_sp, "this is not `async`");
650 let span = self.mark_span_with_reason(DesugaringKind::Await, dot_await_span, None);
651 let gen_future_span = self.mark_span_with_reason(
652 DesugaringKind::Await,
654 self.allow_gen_future.clone(),
656 let expr = self.lower_expr_mut(expr);
657 let expr_hir_id = expr.hir_id;
659 // Note that the name of this binding must not be changed to something else because
660 // debuggers and debugger extensions expect it to be called `__awaitee`. They use
661 // this name to identify what is being awaited by a suspended async functions.
662 let awaitee_ident = Ident::with_dummy_span(sym::__awaitee);
663 let (awaitee_pat, awaitee_pat_hid) =
664 self.pat_ident_binding_mode(span, awaitee_ident, hir::BindingAnnotation::Mutable);
666 let task_context_ident = Ident::with_dummy_span(sym::_task_context);
669 // ::std::future::Future::poll(
670 // ::std::pin::Pin::new_unchecked(&mut __awaitee),
671 // ::std::future::get_context(task_context),
675 let awaitee = self.expr_ident(span, awaitee_ident, awaitee_pat_hid);
676 let ref_mut_awaitee = self.expr_mut_addr_of(span, awaitee);
677 let task_context = if let Some(task_context_hid) = self.task_context {
678 self.expr_ident_mut(span, task_context_ident, task_context_hid)
680 // Use of `await` outside of an async context, we cannot use `task_context` here.
683 let new_unchecked = self.expr_call_lang_item_fn_mut(
685 hir::LangItem::PinNewUnchecked,
686 arena_vec![self; ref_mut_awaitee],
689 let get_context = self.expr_call_lang_item_fn_mut(
691 hir::LangItem::GetContext,
692 arena_vec![self; task_context],
695 let call = self.expr_call_lang_item_fn(
697 hir::LangItem::FuturePoll,
698 arena_vec![self; new_unchecked, get_context],
701 self.arena.alloc(self.expr_unsafe(call))
704 // `::std::task::Poll::Ready(result) => break result`
705 let loop_node_id = self.resolver.next_node_id();
706 let loop_hir_id = self.lower_node_id(loop_node_id);
708 let x_ident = Ident::with_dummy_span(sym::result);
709 let (x_pat, x_pat_hid) = self.pat_ident(gen_future_span, x_ident);
710 let x_expr = self.expr_ident(gen_future_span, x_ident, x_pat_hid);
711 let ready_field = self.single_pat_field(gen_future_span, x_pat);
712 let ready_pat = self.pat_lang_item_variant(
714 hir::LangItem::PollReady,
718 let break_x = self.with_loop_scope(loop_node_id, move |this| {
720 hir::ExprKind::Break(this.lower_loop_destination(None), Some(x_expr));
721 this.arena.alloc(this.expr(gen_future_span, expr_break, ThinVec::new()))
723 self.arm(ready_pat, break_x)
726 // `::std::task::Poll::Pending => {}`
728 let pending_pat = self.pat_lang_item_variant(
730 hir::LangItem::PollPending,
734 let empty_block = self.expr_block_empty(span);
735 self.arm(pending_pat, empty_block)
738 let inner_match_stmt = {
739 let match_expr = self.expr_match(
742 arena_vec![self; ready_arm, pending_arm],
743 hir::MatchSource::AwaitDesugar,
745 self.stmt_expr(span, match_expr)
748 // task_context = yield ();
750 let unit = self.expr_unit(span);
751 let yield_expr = self.expr(
753 hir::ExprKind::Yield(unit, hir::YieldSource::Await { expr: Some(expr_hir_id) }),
756 let yield_expr = self.arena.alloc(yield_expr);
758 if let Some(task_context_hid) = self.task_context {
759 let lhs = self.expr_ident(span, task_context_ident, task_context_hid);
760 let assign = self.expr(
762 hir::ExprKind::Assign(lhs, yield_expr, self.lower_span(span)),
765 self.stmt_expr(span, assign)
767 // Use of `await` outside of an async context. Return `yield_expr` so that we can
768 // proceed with type checking.
769 self.stmt(span, hir::StmtKind::Semi(yield_expr))
773 let loop_block = self.block_all(span, arena_vec![self; inner_match_stmt, yield_stmt], None);
776 let loop_expr = self.arena.alloc(hir::Expr {
778 kind: hir::ExprKind::Loop(
781 hir::LoopSource::Loop,
782 self.lower_span(span),
784 span: self.lower_span(span),
787 // mut __awaitee => loop { ... }
788 let awaitee_arm = self.arm(awaitee_pat, loop_expr);
790 // `match ::std::future::IntoFuture::into_future(<expr>) { ... }`
791 let into_future_span = self.mark_span_with_reason(
792 DesugaringKind::Await,
794 self.allow_into_future.clone(),
796 let into_future_expr = self.expr_call_lang_item_fn(
798 hir::LangItem::IntoFutureIntoFuture,
799 arena_vec![self; expr],
803 // match <into_future_expr> {
804 // mut __awaitee => loop { .. }
806 hir::ExprKind::Match(
808 arena_vec![self; awaitee_arm],
809 hir::MatchSource::AwaitDesugar,
813 fn lower_expr_closure(
815 capture_clause: CaptureBy,
816 movability: Movability,
820 ) -> hir::ExprKind<'hir> {
821 let (body_id, generator_option) = self.with_new_scopes(move |this| {
822 let prev = this.current_item;
823 this.current_item = Some(fn_decl_span);
824 let mut generator_kind = None;
825 let body_id = this.lower_fn_body(decl, |this| {
826 let e = this.lower_expr_mut(body);
827 generator_kind = this.generator_kind;
830 let generator_option =
831 this.generator_movability_for_fn(&decl, fn_decl_span, generator_kind, movability);
832 this.current_item = prev;
833 (body_id, generator_option)
836 // Lower outside new scope to preserve `is_in_loop_condition`.
837 let fn_decl = self.lower_fn_decl(decl, None, FnDeclKind::Closure, None);
839 hir::ExprKind::Closure(
843 self.lower_span(fn_decl_span),
848 fn generator_movability_for_fn(
852 generator_kind: Option<hir::GeneratorKind>,
853 movability: Movability,
854 ) -> Option<hir::Movability> {
855 match generator_kind {
856 Some(hir::GeneratorKind::Gen) => {
857 if decl.inputs.len() > 1 {
862 "too many parameters for a generator (expected 0 or 1 parameters)"
868 Some(hir::GeneratorKind::Async(_)) => {
869 panic!("non-`async` closure body turned `async` during lowering");
872 if movability == Movability::Static {
873 struct_span_err!(self.sess, fn_decl_span, E0697, "closures cannot be static")
881 fn lower_expr_async_closure(
883 capture_clause: CaptureBy,
888 ) -> hir::ExprKind<'hir> {
890 FnDecl { inputs: decl.inputs.clone(), output: FnRetTy::Default(fn_decl_span) };
892 let body_id = self.with_new_scopes(|this| {
893 // FIXME(cramertj): allow `async` non-`move` closures with arguments.
894 if capture_clause == CaptureBy::Ref && !decl.inputs.is_empty() {
899 "`async` non-`move` closures with parameters are not currently supported",
902 "consider using `let` statements to manually capture \
903 variables by reference before entering an `async move` closure",
908 // Transform `async |x: u8| -> X { ... }` into
909 // `|x: u8| future_from_generator(|| -> X { ... })`.
910 let body_id = this.lower_fn_body(&outer_decl, |this| {
912 if let FnRetTy::Ty(ty) = &decl.output { Some(ty.clone()) } else { None };
913 let async_body = this.make_async_expr(
918 hir::AsyncGeneratorKind::Closure,
919 |this| this.with_new_scopes(|this| this.lower_expr_mut(body)),
921 this.expr(fn_decl_span, async_body, ThinVec::new())
926 // We need to lower the declaration outside the new scope, because we
927 // have to conserve the state of being inside a loop condition for the
928 // closure argument types.
929 let fn_decl = self.lower_fn_decl(&outer_decl, None, FnDeclKind::Closure, None);
931 hir::ExprKind::Closure(
935 self.lower_span(fn_decl_span),
940 /// Destructure the LHS of complex assignments.
941 /// For instance, lower `(a, b) = t` to `{ let (lhs1, lhs2) = t; a = lhs1; b = lhs2; }`.
942 fn lower_expr_assign(
948 ) -> hir::ExprKind<'hir> {
949 // Return early in case of an ordinary assignment.
950 fn is_ordinary(lower_ctx: &mut LoweringContext<'_, '_>, lhs: &Expr) -> bool {
953 | ExprKind::Struct(..)
955 | ExprKind::Underscore => false,
956 // Check for tuple struct constructor.
957 ExprKind::Call(callee, ..) => lower_ctx.extract_tuple_struct_path(callee).is_none(),
958 ExprKind::Paren(e) => {
960 // We special-case `(..)` for consistency with patterns.
961 ExprKind::Range(None, None, RangeLimits::HalfOpen) => false,
962 _ => is_ordinary(lower_ctx, e),
968 if is_ordinary(self, lhs) {
969 return hir::ExprKind::Assign(
970 self.lower_expr(lhs),
971 self.lower_expr(rhs),
972 self.lower_span(eq_sign_span),
976 let mut assignments = vec![];
978 // The LHS becomes a pattern: `(lhs1, lhs2)`.
979 let pat = self.destructure_assign(lhs, eq_sign_span, &mut assignments);
980 let rhs = self.lower_expr(rhs);
982 // Introduce a `let` for destructuring: `let (lhs1, lhs2) = t`.
983 let destructure_let = self.stmt_let_pat(
988 hir::LocalSource::AssignDesugar(self.lower_span(eq_sign_span)),
991 // `a = lhs1; b = lhs2;`.
994 .alloc_from_iter(std::iter::once(destructure_let).chain(assignments.into_iter()));
996 // Wrap everything in a block.
997 hir::ExprKind::Block(&self.block_all(whole_span, stmts, None), None)
1000 /// If the given expression is a path to a tuple struct, returns that path.
1001 /// It is not a complete check, but just tries to reject most paths early
1002 /// if they are not tuple structs.
1003 /// Type checking will take care of the full validation later.
1004 fn extract_tuple_struct_path<'a>(
1007 ) -> Option<(&'a Option<QSelf>, &'a Path)> {
1008 if let ExprKind::Path(qself, path) = &expr.kind {
1009 // Does the path resolve to something disallowed in a tuple struct/variant pattern?
1010 if let Some(partial_res) = self.resolver.get_partial_res(expr.id) {
1011 if partial_res.unresolved_segments() == 0
1012 && !partial_res.base_res().expected_in_tuple_struct_pat()
1017 return Some((qself, path));
1022 /// Convert the LHS of a destructuring assignment to a pattern.
1023 /// Each sub-assignment is recorded in `assignments`.
1024 fn destructure_assign(
1028 assignments: &mut Vec<hir::Stmt<'hir>>,
1029 ) -> &'hir hir::Pat<'hir> {
1030 self.arena.alloc(self.destructure_assign_mut(lhs, eq_sign_span, assignments))
1033 fn destructure_assign_mut(
1037 assignments: &mut Vec<hir::Stmt<'hir>>,
1038 ) -> hir::Pat<'hir> {
1040 // Underscore pattern.
1041 ExprKind::Underscore => {
1042 return self.pat_without_dbm(lhs.span, hir::PatKind::Wild);
1045 ExprKind::Array(elements) => {
1047 self.destructure_sequence(elements, "slice", eq_sign_span, assignments);
1048 let slice_pat = if let Some((i, span)) = rest {
1049 let (before, after) = pats.split_at(i);
1050 hir::PatKind::Slice(
1052 Some(self.arena.alloc(self.pat_without_dbm(span, hir::PatKind::Wild))),
1056 hir::PatKind::Slice(pats, None, &[])
1058 return self.pat_without_dbm(lhs.span, slice_pat);
1061 ExprKind::Call(callee, args) => {
1062 if let Some((qself, path)) = self.extract_tuple_struct_path(callee) {
1063 let (pats, rest) = self.destructure_sequence(
1065 "tuple struct or variant",
1069 let qpath = self.lower_qpath(
1073 ParamMode::Optional,
1074 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1076 // Destructure like a tuple struct.
1077 let tuple_struct_pat =
1078 hir::PatKind::TupleStruct(qpath, pats, rest.map(|r| r.0));
1079 return self.pat_without_dbm(lhs.span, tuple_struct_pat);
1083 ExprKind::Struct(se) => {
1084 let field_pats = self.arena.alloc_from_iter(se.fields.iter().map(|f| {
1085 let pat = self.destructure_assign(&f.expr, eq_sign_span, assignments);
1087 hir_id: self.next_id(),
1088 ident: self.lower_ident(f.ident),
1090 is_shorthand: f.is_shorthand,
1091 span: self.lower_span(f.span),
1094 let qpath = self.lower_qpath(
1098 ParamMode::Optional,
1099 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1101 let fields_omitted = match &se.rest {
1102 StructRest::Base(e) => {
1106 "functional record updates are not allowed in destructuring \
1111 "consider removing the trailing pattern",
1113 rustc_errors::Applicability::MachineApplicable,
1118 StructRest::Rest(_) => true,
1119 StructRest::None => false,
1121 let struct_pat = hir::PatKind::Struct(qpath, field_pats, fields_omitted);
1122 return self.pat_without_dbm(lhs.span, struct_pat);
1125 ExprKind::Tup(elements) => {
1127 self.destructure_sequence(elements, "tuple", eq_sign_span, assignments);
1128 let tuple_pat = hir::PatKind::Tuple(pats, rest.map(|r| r.0));
1129 return self.pat_without_dbm(lhs.span, tuple_pat);
1131 ExprKind::Paren(e) => {
1132 // We special-case `(..)` for consistency with patterns.
1133 if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
1134 let tuple_pat = hir::PatKind::Tuple(&[], Some(0));
1135 return self.pat_without_dbm(lhs.span, tuple_pat);
1137 return self.destructure_assign_mut(e, eq_sign_span, assignments);
1142 // Treat all other cases as normal lvalue.
1143 let ident = Ident::new(sym::lhs, self.lower_span(lhs.span));
1144 let (pat, binding) = self.pat_ident_mut(lhs.span, ident);
1145 let ident = self.expr_ident(lhs.span, ident, binding);
1147 hir::ExprKind::Assign(self.lower_expr(lhs), ident, self.lower_span(eq_sign_span));
1148 let expr = self.expr(lhs.span, assign, ThinVec::new());
1149 assignments.push(self.stmt_expr(lhs.span, expr));
1153 /// Destructure a sequence of expressions occurring on the LHS of an assignment.
1154 /// Such a sequence occurs in a tuple (struct)/slice.
1155 /// Return a sequence of corresponding patterns, and the index and the span of `..` if it
1157 /// Each sub-assignment is recorded in `assignments`.
1158 fn destructure_sequence(
1160 elements: &[AstP<Expr>],
1163 assignments: &mut Vec<hir::Stmt<'hir>>,
1164 ) -> (&'hir [hir::Pat<'hir>], Option<(usize, Span)>) {
1165 let mut rest = None;
1167 self.arena.alloc_from_iter(elements.iter().enumerate().filter_map(|(i, e)| {
1168 // Check for `..` pattern.
1169 if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
1170 if let Some((_, prev_span)) = rest {
1171 self.ban_extra_rest_pat(e.span, prev_span, ctx);
1173 rest = Some((i, e.span));
1177 Some(self.destructure_assign_mut(e, eq_sign_span, assignments))
1183 /// Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`.
1184 fn lower_expr_range_closed(&mut self, span: Span, e1: &Expr, e2: &Expr) -> hir::ExprKind<'hir> {
1185 let e1 = self.lower_expr_mut(e1);
1186 let e2 = self.lower_expr_mut(e2);
1188 hir::QPath::LangItem(hir::LangItem::RangeInclusiveNew, self.lower_span(span), None);
1190 self.arena.alloc(self.expr(span, hir::ExprKind::Path(fn_path), ThinVec::new()));
1191 hir::ExprKind::Call(fn_expr, arena_vec![self; e1, e2])
1194 fn lower_expr_range(
1200 ) -> hir::ExprKind<'hir> {
1201 use rustc_ast::RangeLimits::*;
1203 let lang_item = match (e1, e2, lims) {
1204 (None, None, HalfOpen) => hir::LangItem::RangeFull,
1205 (Some(..), None, HalfOpen) => hir::LangItem::RangeFrom,
1206 (None, Some(..), HalfOpen) => hir::LangItem::RangeTo,
1207 (Some(..), Some(..), HalfOpen) => hir::LangItem::Range,
1208 (None, Some(..), Closed) => hir::LangItem::RangeToInclusive,
1209 (Some(..), Some(..), Closed) => unreachable!(),
1210 (_, None, Closed) => self.diagnostic().span_fatal(span, "inclusive range with no end"),
1213 let fields = self.arena.alloc_from_iter(
1214 e1.iter().map(|e| (sym::start, e)).chain(e2.iter().map(|e| (sym::end, e))).map(
1216 let expr = self.lower_expr(&e);
1217 let ident = Ident::new(s, self.lower_span(e.span));
1218 self.expr_field(ident, expr, e.span)
1223 hir::ExprKind::Struct(
1224 self.arena.alloc(hir::QPath::LangItem(lang_item, self.lower_span(span), None)),
1230 fn lower_label(&self, opt_label: Option<Label>) -> Option<Label> {
1231 let label = opt_label?;
1232 Some(Label { ident: self.lower_ident(label.ident) })
1235 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
1236 let target_id = match destination {
1238 if let Some(loop_id) = self.resolver.get_label_res(id) {
1239 Ok(self.lower_node_id(loop_id))
1241 Err(hir::LoopIdError::UnresolvedLabel)
1246 .map(|id| Ok(self.lower_node_id(id)))
1247 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope)),
1249 let label = self.lower_label(destination.map(|(_, label)| label));
1250 hir::Destination { label, target_id }
1253 fn lower_jump_destination(&mut self, id: NodeId, opt_label: Option<Label>) -> hir::Destination {
1254 if self.is_in_loop_condition && opt_label.is_none() {
1257 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition),
1260 self.lower_loop_destination(opt_label.map(|label| (id, label)))
1264 fn with_catch_scope<T>(&mut self, catch_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1265 let old_scope = self.catch_scope.replace(catch_id);
1266 let result = f(self);
1267 self.catch_scope = old_scope;
1271 fn with_loop_scope<T>(&mut self, loop_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1272 // We're no longer in the base loop's condition; we're in another loop.
1273 let was_in_loop_condition = self.is_in_loop_condition;
1274 self.is_in_loop_condition = false;
1276 let old_scope = self.loop_scope.replace(loop_id);
1277 let result = f(self);
1278 self.loop_scope = old_scope;
1280 self.is_in_loop_condition = was_in_loop_condition;
1285 fn with_loop_condition_scope<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
1286 let was_in_loop_condition = self.is_in_loop_condition;
1287 self.is_in_loop_condition = true;
1289 let result = f(self);
1291 self.is_in_loop_condition = was_in_loop_condition;
1296 fn lower_expr_field(&mut self, f: &ExprField) -> hir::ExprField<'hir> {
1298 hir_id: self.next_id(),
1299 ident: self.lower_ident(f.ident),
1300 expr: self.lower_expr(&f.expr),
1301 span: self.lower_span(f.span),
1302 is_shorthand: f.is_shorthand,
1306 fn lower_expr_yield(&mut self, span: Span, opt_expr: Option<&Expr>) -> hir::ExprKind<'hir> {
1307 match self.generator_kind {
1308 Some(hir::GeneratorKind::Gen) => {}
1309 Some(hir::GeneratorKind::Async(_)) => {
1314 "`async` generators are not yet supported"
1318 None => self.generator_kind = Some(hir::GeneratorKind::Gen),
1322 opt_expr.as_ref().map(|x| self.lower_expr(x)).unwrap_or_else(|| self.expr_unit(span));
1324 hir::ExprKind::Yield(expr, hir::YieldSource::Yield)
1327 /// Desugar `ExprForLoop` from: `[opt_ident]: for <pat> in <head> <body>` into:
1328 /// ```ignore (pseudo-rust)
1330 /// let result = match IntoIterator::into_iter(<head>) {
1332 /// [opt_ident]: loop {
1333 /// match Iterator::next(&mut iter) {
1335 /// Some(<pat>) => <body>,
1349 opt_label: Option<Label>,
1350 ) -> hir::Expr<'hir> {
1351 let head = self.lower_expr_mut(head);
1352 let pat = self.lower_pat(pat);
1354 self.mark_span_with_reason(DesugaringKind::ForLoop, self.lower_span(e.span), None);
1355 let head_span = self.mark_span_with_reason(DesugaringKind::ForLoop, head.span, None);
1356 let pat_span = self.mark_span_with_reason(DesugaringKind::ForLoop, pat.span, None);
1361 self.with_loop_scope(e.id, |this| this.expr_break_alloc(for_span, ThinVec::new()));
1362 let pat = self.pat_none(for_span);
1363 self.arm(pat, break_expr)
1366 // Some(<pat>) => <body>,
1368 let some_pat = self.pat_some(pat_span, pat);
1369 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
1370 let body_expr = self.arena.alloc(self.expr_block(body_block, ThinVec::new()));
1371 self.arm(some_pat, body_expr)
1375 let iter = Ident::with_dummy_span(sym::iter);
1376 let (iter_pat, iter_pat_nid) =
1377 self.pat_ident_binding_mode(head_span, iter, hir::BindingAnnotation::Mutable);
1379 // `match Iterator::next(&mut iter) { ... }`
1381 let iter = self.expr_ident(head_span, iter, iter_pat_nid);
1382 let ref_mut_iter = self.expr_mut_addr_of(head_span, iter);
1383 let next_expr = self.expr_call_lang_item_fn(
1385 hir::LangItem::IteratorNext,
1386 arena_vec![self; ref_mut_iter],
1389 let arms = arena_vec![self; none_arm, some_arm];
1391 self.expr_match(head_span, next_expr, arms, hir::MatchSource::ForLoopDesugar)
1393 let match_stmt = self.stmt_expr(for_span, match_expr);
1395 let loop_block = self.block_all(for_span, arena_vec![self; match_stmt], None);
1397 // `[opt_ident]: loop { ... }`
1398 let kind = hir::ExprKind::Loop(
1400 self.lower_label(opt_label),
1401 hir::LoopSource::ForLoop,
1402 self.lower_span(for_span.with_hi(head.span.hi())),
1405 self.arena.alloc(hir::Expr { hir_id: self.lower_node_id(e.id), kind, span: for_span });
1407 // `mut iter => { ... }`
1408 let iter_arm = self.arm(iter_pat, loop_expr);
1410 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
1411 let into_iter_expr = {
1412 self.expr_call_lang_item_fn(
1414 hir::LangItem::IntoIterIntoIter,
1415 arena_vec![self; head],
1420 let match_expr = self.arena.alloc(self.expr_match(
1423 arena_vec![self; iter_arm],
1424 hir::MatchSource::ForLoopDesugar,
1427 let attrs: Vec<_> = e.attrs.iter().map(|a| self.lower_attr(a)).collect();
1429 // This is effectively `{ let _result = ...; _result }`.
1430 // The construct was introduced in #21984 and is necessary to make sure that
1431 // temporaries in the `head` expression are dropped and do not leak to the
1432 // surrounding scope of the `match` since the `match` is not a terminating scope.
1434 // Also, add the attributes to the outer returned expr node.
1435 self.expr_drop_temps_mut(for_span, match_expr, attrs.into())
1438 /// Desugar `ExprKind::Try` from: `<expr>?` into:
1439 /// ```ignore (pseudo-rust)
1440 /// match Try::branch(<expr>) {
1441 /// ControlFlow::Continue(val) => #[allow(unreachable_code)] val,,
1442 /// ControlFlow::Break(residual) =>
1443 /// #[allow(unreachable_code)]
1444 /// // If there is an enclosing `try {...}`:
1445 /// break 'catch_target Try::from_residual(residual),
1447 /// return Try::from_residual(residual),
1450 fn lower_expr_try(&mut self, span: Span, sub_expr: &Expr) -> hir::ExprKind<'hir> {
1451 let unstable_span = self.mark_span_with_reason(
1452 DesugaringKind::QuestionMark,
1454 self.allow_try_trait.clone(),
1456 let try_span = self.sess.source_map().end_point(span);
1457 let try_span = self.mark_span_with_reason(
1458 DesugaringKind::QuestionMark,
1460 self.allow_try_trait.clone(),
1463 // `Try::branch(<expr>)`
1466 let sub_expr = self.lower_expr_mut(sub_expr);
1468 self.expr_call_lang_item_fn(
1470 hir::LangItem::TryTraitBranch,
1471 arena_vec![self; sub_expr],
1476 // `#[allow(unreachable_code)]`
1478 // `allow(unreachable_code)`
1480 let allow_ident = Ident::new(sym::allow, self.lower_span(span));
1481 let uc_ident = Ident::new(sym::unreachable_code, self.lower_span(span));
1482 let uc_nested = attr::mk_nested_word_item(uc_ident);
1483 attr::mk_list_item(allow_ident, vec![uc_nested])
1485 attr::mk_attr_outer(allow)
1487 let attrs = vec![attr];
1489 // `ControlFlow::Continue(val) => #[allow(unreachable_code)] val,`
1490 let continue_arm = {
1491 let val_ident = Ident::with_dummy_span(sym::val);
1492 let (val_pat, val_pat_nid) = self.pat_ident(span, val_ident);
1493 let val_expr = self.arena.alloc(self.expr_ident_with_attrs(
1497 ThinVec::from(attrs.clone()),
1499 let continue_pat = self.pat_cf_continue(unstable_span, val_pat);
1500 self.arm(continue_pat, val_expr)
1503 // `ControlFlow::Break(residual) =>
1504 // #[allow(unreachable_code)]
1505 // return Try::from_residual(residual),`
1507 let residual_ident = Ident::with_dummy_span(sym::residual);
1508 let (residual_local, residual_local_nid) = self.pat_ident(try_span, residual_ident);
1509 let residual_expr = self.expr_ident_mut(try_span, residual_ident, residual_local_nid);
1510 let from_residual_expr = self.wrap_in_try_constructor(
1511 hir::LangItem::TryTraitFromResidual,
1513 self.arena.alloc(residual_expr),
1516 let thin_attrs = ThinVec::from(attrs);
1517 let ret_expr = if let Some(catch_node) = self.catch_scope {
1518 let target_id = Ok(self.lower_node_id(catch_node));
1519 self.arena.alloc(self.expr(
1521 hir::ExprKind::Break(
1522 hir::Destination { label: None, target_id },
1523 Some(from_residual_expr),
1528 self.arena.alloc(self.expr(
1530 hir::ExprKind::Ret(Some(from_residual_expr)),
1535 let break_pat = self.pat_cf_break(try_span, residual_local);
1536 self.arm(break_pat, ret_expr)
1539 hir::ExprKind::Match(
1541 arena_vec![self; break_arm, continue_arm],
1542 hir::MatchSource::TryDesugar,
1546 // =========================================================================
1547 // Helper methods for building HIR.
1548 // =========================================================================
1550 /// Wrap the given `expr` in a terminating scope using `hir::ExprKind::DropTemps`.
1552 /// In terms of drop order, it has the same effect as wrapping `expr` in
1553 /// `{ let _t = $expr; _t }` but should provide better compile-time performance.
1555 /// The drop order can be important in e.g. `if expr { .. }`.
1556 pub(super) fn expr_drop_temps(
1559 expr: &'hir hir::Expr<'hir>,
1561 ) -> &'hir hir::Expr<'hir> {
1562 self.arena.alloc(self.expr_drop_temps_mut(span, expr, attrs))
1565 pub(super) fn expr_drop_temps_mut(
1568 expr: &'hir hir::Expr<'hir>,
1570 ) -> hir::Expr<'hir> {
1571 self.expr(span, hir::ExprKind::DropTemps(expr), attrs)
1577 arg: &'hir hir::Expr<'hir>,
1578 arms: &'hir [hir::Arm<'hir>],
1579 source: hir::MatchSource,
1580 ) -> hir::Expr<'hir> {
1581 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
1584 fn expr_break(&mut self, span: Span, attrs: AttrVec) -> hir::Expr<'hir> {
1585 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
1586 self.expr(span, expr_break, attrs)
1589 fn expr_break_alloc(&mut self, span: Span, attrs: AttrVec) -> &'hir hir::Expr<'hir> {
1590 let expr_break = self.expr_break(span, attrs);
1591 self.arena.alloc(expr_break)
1594 fn expr_mut_addr_of(&mut self, span: Span, e: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
1597 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Mut, e),
1602 fn expr_unit(&mut self, sp: Span) -> &'hir hir::Expr<'hir> {
1603 self.arena.alloc(self.expr(sp, hir::ExprKind::Tup(&[]), ThinVec::new()))
1609 e: &'hir hir::Expr<'hir>,
1610 args: &'hir [hir::Expr<'hir>],
1611 ) -> hir::Expr<'hir> {
1612 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
1618 e: &'hir hir::Expr<'hir>,
1619 args: &'hir [hir::Expr<'hir>],
1620 ) -> &'hir hir::Expr<'hir> {
1621 self.arena.alloc(self.expr_call_mut(span, e, args))
1624 fn expr_call_lang_item_fn_mut(
1627 lang_item: hir::LangItem,
1628 args: &'hir [hir::Expr<'hir>],
1629 hir_id: Option<hir::HirId>,
1630 ) -> hir::Expr<'hir> {
1632 self.arena.alloc(self.expr_lang_item_path(span, lang_item, ThinVec::new(), hir_id));
1633 self.expr_call_mut(span, path, args)
1636 fn expr_call_lang_item_fn(
1639 lang_item: hir::LangItem,
1640 args: &'hir [hir::Expr<'hir>],
1641 hir_id: Option<hir::HirId>,
1642 ) -> &'hir hir::Expr<'hir> {
1643 self.arena.alloc(self.expr_call_lang_item_fn_mut(span, lang_item, args, hir_id))
1646 fn expr_lang_item_path(
1649 lang_item: hir::LangItem,
1651 hir_id: Option<hir::HirId>,
1652 ) -> hir::Expr<'hir> {
1655 hir::ExprKind::Path(hir::QPath::LangItem(lang_item, self.lower_span(span), hir_id)),
1660 pub(super) fn expr_ident(
1664 binding: hir::HirId,
1665 ) -> &'hir hir::Expr<'hir> {
1666 self.arena.alloc(self.expr_ident_mut(sp, ident, binding))
1669 pub(super) fn expr_ident_mut(
1673 binding: hir::HirId,
1674 ) -> hir::Expr<'hir> {
1675 self.expr_ident_with_attrs(sp, ident, binding, ThinVec::new())
1678 fn expr_ident_with_attrs(
1682 binding: hir::HirId,
1684 ) -> hir::Expr<'hir> {
1685 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
1687 self.arena.alloc(hir::Path {
1688 span: self.lower_span(span),
1689 res: Res::Local(binding),
1690 segments: arena_vec![self; hir::PathSegment::from_ident(ident)],
1694 self.expr(span, expr_path, attrs)
1697 fn expr_unsafe(&mut self, expr: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
1698 let hir_id = self.next_id();
1699 let span = expr.span;
1702 hir::ExprKind::Block(
1703 self.arena.alloc(hir::Block {
1707 rules: hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::CompilerGenerated),
1708 span: self.lower_span(span),
1709 targeted_by_break: false,
1717 fn expr_block_empty(&mut self, span: Span) -> &'hir hir::Expr<'hir> {
1718 let blk = self.block_all(span, &[], None);
1719 let expr = self.expr_block(blk, ThinVec::new());
1720 self.arena.alloc(expr)
1723 pub(super) fn expr_block(
1725 b: &'hir hir::Block<'hir>,
1727 ) -> hir::Expr<'hir> {
1728 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
1734 kind: hir::ExprKind<'hir>,
1736 ) -> hir::Expr<'hir> {
1737 let hir_id = self.next_id();
1738 self.lower_attrs(hir_id, &attrs);
1739 hir::Expr { hir_id, kind, span: self.lower_span(span) }
1745 expr: &'hir hir::Expr<'hir>,
1747 ) -> hir::ExprField<'hir> {
1749 hir_id: self.next_id(),
1751 span: self.lower_span(span),
1753 is_shorthand: false,
1757 fn arm(&mut self, pat: &'hir hir::Pat<'hir>, expr: &'hir hir::Expr<'hir>) -> hir::Arm<'hir> {
1759 hir_id: self.next_id(),
1762 span: self.lower_span(expr.span),