1 use super::{ImplTraitContext, LoweringContext, ParamMode, ParenthesizedGenericArgs};
4 use rustc_ast::ptr::P as AstP;
6 use rustc_data_structures::stack::ensure_sufficient_stack;
7 use rustc_data_structures::thin_vec::ThinVec;
8 use rustc_errors::struct_span_err;
10 use rustc_hir::def::Res;
11 use rustc_hir::definitions::DefPathData;
12 use rustc_session::parse::feature_err;
13 use rustc_span::hygiene::ExpnId;
14 use rustc_span::source_map::{respan, DesugaringKind, Span, Spanned};
15 use rustc_span::symbol::{sym, Ident, Symbol};
16 use rustc_span::{hygiene::ForLoopLoc, DUMMY_SP};
18 impl<'hir> LoweringContext<'_, 'hir> {
19 fn lower_exprs(&mut self, exprs: &[AstP<Expr>]) -> &'hir [hir::Expr<'hir>] {
20 self.arena.alloc_from_iter(exprs.iter().map(|x| self.lower_expr_mut(x)))
23 pub(super) fn lower_expr(&mut self, e: &Expr) -> &'hir hir::Expr<'hir> {
24 self.arena.alloc(self.lower_expr_mut(e))
27 pub(super) fn lower_expr_mut(&mut self, e: &Expr) -> hir::Expr<'hir> {
28 ensure_sufficient_stack(|| {
29 let kind = match e.kind {
30 ExprKind::Box(ref inner) => hir::ExprKind::Box(self.lower_expr(inner)),
31 ExprKind::Array(ref exprs) => hir::ExprKind::Array(self.lower_exprs(exprs)),
32 ExprKind::ConstBlock(ref anon_const) => {
33 let anon_const = self.lower_anon_const(anon_const);
34 hir::ExprKind::ConstBlock(anon_const)
36 ExprKind::Repeat(ref expr, ref count) => {
37 let expr = self.lower_expr(expr);
38 let count = self.lower_anon_const(count);
39 hir::ExprKind::Repeat(expr, count)
41 ExprKind::Tup(ref elts) => hir::ExprKind::Tup(self.lower_exprs(elts)),
42 ExprKind::Call(ref f, ref args) => {
43 if let Some(legacy_args) = self.resolver.legacy_const_generic_args(f) {
44 self.lower_legacy_const_generics((**f).clone(), args.clone(), &legacy_args)
46 let f = self.lower_expr(f);
47 hir::ExprKind::Call(f, self.lower_exprs(args))
50 ExprKind::MethodCall(ref seg, ref args, span) => {
51 let hir_seg = self.arena.alloc(self.lower_path_segment(
56 ParenthesizedGenericArgs::Err,
57 ImplTraitContext::disallowed(),
59 let args = self.lower_exprs(args);
60 hir::ExprKind::MethodCall(
62 self.lower_span(seg.ident.span),
64 self.lower_span(span),
67 ExprKind::Binary(binop, ref lhs, ref rhs) => {
68 let binop = self.lower_binop(binop);
69 let lhs = self.lower_expr(lhs);
70 let rhs = self.lower_expr(rhs);
71 hir::ExprKind::Binary(binop, lhs, rhs)
73 ExprKind::Unary(op, ref ohs) => {
74 let op = self.lower_unop(op);
75 let ohs = self.lower_expr(ohs);
76 hir::ExprKind::Unary(op, ohs)
78 ExprKind::Lit(ref l) => {
79 hir::ExprKind::Lit(respan(self.lower_span(l.span), l.kind.clone()))
81 ExprKind::Cast(ref expr, ref ty) => {
82 let expr = self.lower_expr(expr);
83 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
84 hir::ExprKind::Cast(expr, ty)
86 ExprKind::Type(ref expr, ref ty) => {
87 let expr = self.lower_expr(expr);
88 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
89 hir::ExprKind::Type(expr, ty)
91 ExprKind::AddrOf(k, m, ref ohs) => {
92 let ohs = self.lower_expr(ohs);
93 hir::ExprKind::AddrOf(k, m, ohs)
95 ExprKind::Let(ref pat, ref scrutinee, span) => hir::ExprKind::Let(
97 self.lower_expr(scrutinee),
98 self.lower_span(span),
100 ExprKind::If(ref cond, ref then, ref else_opt) => {
101 self.lower_expr_if(cond, then, else_opt.as_deref())
103 ExprKind::While(ref cond, ref body, opt_label) => {
104 self.with_loop_scope(e.id, |this| {
106 this.mark_span_with_reason(DesugaringKind::WhileLoop, e.span, None);
107 this.lower_expr_while_in_loop_scope(span, cond, body, opt_label)
110 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
112 this.lower_block(body, false),
113 this.lower_label(opt_label),
114 hir::LoopSource::Loop,
118 ExprKind::TryBlock(ref body) => self.lower_expr_try_block(body),
119 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
120 self.lower_expr(expr),
121 self.arena.alloc_from_iter(arms.iter().map(|x| self.lower_arm(x))),
122 hir::MatchSource::Normal,
124 ExprKind::Async(capture_clause, closure_node_id, ref block) => self
130 hir::AsyncGeneratorKind::Block,
131 |this| this.with_new_scopes(|this| this.lower_block_expr(block)),
133 ExprKind::Await(ref expr) => self.lower_expr_await(e.span, expr),
142 if let Async::Yes { closure_id, .. } = asyncness {
143 self.lower_expr_async_closure(
151 self.lower_expr_closure(
160 ExprKind::Block(ref blk, opt_label) => {
161 let opt_label = self.lower_label(opt_label);
162 hir::ExprKind::Block(self.lower_block(blk, opt_label.is_some()), opt_label)
164 ExprKind::Assign(ref el, ref er, span) => {
165 self.lower_expr_assign(el, er, span, e.span)
167 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
168 self.lower_binop(op),
172 ExprKind::Field(ref el, ident) => {
173 hir::ExprKind::Field(self.lower_expr(el), self.lower_ident(ident))
175 ExprKind::Index(ref el, ref er) => {
176 hir::ExprKind::Index(self.lower_expr(el), self.lower_expr(er))
178 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
179 self.lower_expr_range_closed(e.span, e1, e2)
181 ExprKind::Range(ref e1, ref e2, lims) => {
182 self.lower_expr_range(e.span, e1.as_deref(), e2.as_deref(), lims)
184 ExprKind::Underscore => {
188 "in expressions, `_` can only be used on the left-hand side of an assignment",
190 .span_label(e.span, "`_` not allowed here")
194 ExprKind::Path(ref qself, ref path) => {
195 let qpath = self.lower_qpath(
200 ImplTraitContext::disallowed(),
202 hir::ExprKind::Path(qpath)
204 ExprKind::Break(opt_label, ref opt_expr) => {
205 let opt_expr = opt_expr.as_ref().map(|x| self.lower_expr(x));
206 hir::ExprKind::Break(self.lower_jump_destination(e.id, opt_label), opt_expr)
208 ExprKind::Continue(opt_label) => {
209 hir::ExprKind::Continue(self.lower_jump_destination(e.id, opt_label))
211 ExprKind::Ret(ref e) => {
212 let e = e.as_ref().map(|x| self.lower_expr(x));
213 hir::ExprKind::Ret(e)
215 ExprKind::InlineAsm(ref asm) => {
216 hir::ExprKind::InlineAsm(self.lower_inline_asm(e.span, asm))
218 ExprKind::LlvmInlineAsm(ref asm) => self.lower_expr_llvm_asm(asm),
219 ExprKind::Struct(ref se) => {
220 let rest = match &se.rest {
221 StructRest::Base(e) => Some(self.lower_expr(e)),
222 StructRest::Rest(sp) => {
224 .struct_span_err(*sp, "base expression required after `..`")
225 .span_label(*sp, "add a base expression here")
227 Some(&*self.arena.alloc(self.expr_err(*sp)))
229 StructRest::None => None,
231 hir::ExprKind::Struct(
232 self.arena.alloc(self.lower_qpath(
237 ImplTraitContext::disallowed(),
240 .alloc_from_iter(se.fields.iter().map(|x| self.lower_expr_field(x))),
244 ExprKind::Yield(ref opt_expr) => self.lower_expr_yield(e.span, opt_expr.as_deref()),
245 ExprKind::Err => hir::ExprKind::Err,
246 ExprKind::Try(ref sub_expr) => self.lower_expr_try(e.span, sub_expr),
247 ExprKind::Paren(ref ex) => {
248 let mut ex = self.lower_expr_mut(ex);
249 // Include parens in span, but only if it is a super-span.
250 if e.span.contains(ex.span) {
251 ex.span = self.lower_span(e.span);
253 // Merge attributes into the inner expression.
254 if !e.attrs.is_empty() {
256 self.attrs.get(&ex.hir_id.local_id).map(|la| *la).unwrap_or(&[]);
259 &*self.arena.alloc_from_iter(
262 .map(|a| self.lower_attr(a))
263 .chain(old_attrs.iter().cloned()),
270 // Desugar `ExprForLoop`
271 // from: `[opt_ident]: for <pat> in <head> <body>`
272 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
273 return self.lower_expr_for(e, pat, head, body, opt_label);
275 ExprKind::MacCall(_) => panic!("{:?} shouldn't exist here", e.span),
278 let hir_id = self.lower_node_id(e.id);
279 self.lower_attrs(hir_id, &e.attrs);
280 hir::Expr { hir_id, kind, span: self.lower_span(e.span) }
284 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
286 UnOp::Deref => hir::UnOp::Deref,
287 UnOp::Not => hir::UnOp::Not,
288 UnOp::Neg => hir::UnOp::Neg,
292 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
295 BinOpKind::Add => hir::BinOpKind::Add,
296 BinOpKind::Sub => hir::BinOpKind::Sub,
297 BinOpKind::Mul => hir::BinOpKind::Mul,
298 BinOpKind::Div => hir::BinOpKind::Div,
299 BinOpKind::Rem => hir::BinOpKind::Rem,
300 BinOpKind::And => hir::BinOpKind::And,
301 BinOpKind::Or => hir::BinOpKind::Or,
302 BinOpKind::BitXor => hir::BinOpKind::BitXor,
303 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
304 BinOpKind::BitOr => hir::BinOpKind::BitOr,
305 BinOpKind::Shl => hir::BinOpKind::Shl,
306 BinOpKind::Shr => hir::BinOpKind::Shr,
307 BinOpKind::Eq => hir::BinOpKind::Eq,
308 BinOpKind::Lt => hir::BinOpKind::Lt,
309 BinOpKind::Le => hir::BinOpKind::Le,
310 BinOpKind::Ne => hir::BinOpKind::Ne,
311 BinOpKind::Ge => hir::BinOpKind::Ge,
312 BinOpKind::Gt => hir::BinOpKind::Gt,
314 span: self.lower_span(b.span),
318 fn lower_legacy_const_generics(
321 args: Vec<AstP<Expr>>,
322 legacy_args_idx: &[usize],
323 ) -> hir::ExprKind<'hir> {
324 let path = match f.kind {
325 ExprKind::Path(None, ref mut path) => path,
329 // Split the arguments into const generics and normal arguments
330 let mut real_args = vec![];
331 let mut generic_args = vec![];
332 for (idx, arg) in args.into_iter().enumerate() {
333 if legacy_args_idx.contains(&idx) {
334 let parent_def_id = self.current_hir_id_owner;
335 let node_id = self.resolver.next_node_id();
337 // Add a definition for the in-band const def.
338 self.resolver.create_def(
341 DefPathData::AnonConst,
346 let anon_const = AnonConst { id: node_id, value: arg };
347 generic_args.push(AngleBracketedArg::Arg(GenericArg::Const(anon_const)));
353 // Add generic args to the last element of the path.
354 let last_segment = path.segments.last_mut().unwrap();
355 assert!(last_segment.args.is_none());
356 last_segment.args = Some(AstP(GenericArgs::AngleBracketed(AngleBracketedArgs {
361 // Now lower everything as normal.
362 let f = self.lower_expr(&f);
363 hir::ExprKind::Call(f, self.lower_exprs(&real_args))
370 else_opt: Option<&Expr>,
371 ) -> hir::ExprKind<'hir> {
372 let lowered_cond = self.lower_expr(cond);
373 let new_cond = self.manage_let_cond(lowered_cond);
374 let then_expr = self.lower_block_expr(then);
375 if let Some(rslt) = else_opt {
376 hir::ExprKind::If(new_cond, self.arena.alloc(then_expr), Some(self.lower_expr(rslt)))
378 hir::ExprKind::If(new_cond, self.arena.alloc(then_expr), None)
382 // If `cond` kind is `let`, returns `let`. Otherwise, wraps and returns `cond`
383 // in a temporary block.
384 fn manage_let_cond(&mut self, cond: &'hir hir::Expr<'hir>) -> &'hir hir::Expr<'hir> {
386 hir::ExprKind::Let(..) => cond,
389 self.mark_span_with_reason(DesugaringKind::CondTemporary, cond.span, None);
390 self.expr_drop_temps(span_block, cond, AttrVec::new())
395 // We desugar: `'label: while $cond $body` into:
399 // if { let _t = $cond; _t } {
408 // Wrap in a construct equivalent to `{ let _t = $cond; _t }`
409 // to preserve drop semantics since `while $cond { ... }` does not
410 // let temporaries live outside of `cond`.
411 fn lower_expr_while_in_loop_scope(
416 opt_label: Option<Label>,
417 ) -> hir::ExprKind<'hir> {
418 let lowered_cond = self.with_loop_condition_scope(|t| t.lower_expr(cond));
419 let new_cond = self.manage_let_cond(lowered_cond);
420 let then = self.lower_block_expr(body);
421 let expr_break = self.expr_break(span, ThinVec::new());
422 let stmt_break = self.stmt_expr(span, expr_break);
423 let else_blk = self.block_all(span, arena_vec![self; stmt_break], None);
424 let else_expr = self.arena.alloc(self.expr_block(else_blk, ThinVec::new()));
425 let if_kind = hir::ExprKind::If(new_cond, self.arena.alloc(then), Some(else_expr));
426 let if_expr = self.expr(span, if_kind, ThinVec::new());
427 let block = self.block_expr(self.arena.alloc(if_expr));
428 let span = self.lower_span(span.with_hi(cond.span.hi()));
429 let opt_label = self.lower_label(opt_label);
430 hir::ExprKind::Loop(block, opt_label, hir::LoopSource::While, span)
433 /// Desugar `try { <stmts>; <expr> }` into `{ <stmts>; ::std::ops::Try::from_output(<expr>) }`,
434 /// `try { <stmts>; }` into `{ <stmts>; ::std::ops::Try::from_output(()) }`
435 /// and save the block id to use it as a break target for desugaring of the `?` operator.
436 fn lower_expr_try_block(&mut self, body: &Block) -> hir::ExprKind<'hir> {
437 self.with_catch_scope(body.id, |this| {
438 let mut block = this.lower_block_noalloc(body, true);
440 // Final expression of the block (if present) or `()` with span at the end of block
441 let (try_span, tail_expr) = if let Some(expr) = block.expr.take() {
443 this.mark_span_with_reason(
444 DesugaringKind::TryBlock,
446 this.allow_try_trait.clone(),
451 let try_span = this.mark_span_with_reason(
452 DesugaringKind::TryBlock,
453 this.sess.source_map().end_point(body.span),
454 this.allow_try_trait.clone(),
457 (try_span, this.expr_unit(try_span))
460 let ok_wrapped_span =
461 this.mark_span_with_reason(DesugaringKind::TryBlock, tail_expr.span, None);
463 // `::std::ops::Try::from_output($tail_expr)`
464 block.expr = Some(this.wrap_in_try_constructor(
465 hir::LangItem::TryTraitFromOutput,
471 hir::ExprKind::Block(this.arena.alloc(block), None)
475 fn wrap_in_try_constructor(
477 lang_item: hir::LangItem,
479 expr: &'hir hir::Expr<'hir>,
481 ) -> &'hir hir::Expr<'hir> {
483 self.arena.alloc(self.expr_lang_item_path(method_span, lang_item, ThinVec::new()));
484 self.expr_call(overall_span, constructor, std::slice::from_ref(expr))
487 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm<'hir> {
488 let pat = self.lower_pat(&arm.pat);
489 let guard = arm.guard.as_ref().map(|cond| {
490 if let ExprKind::Let(ref pat, ref scrutinee, _) = cond.kind {
491 hir::Guard::IfLet(self.lower_pat(pat), self.lower_expr(scrutinee))
493 hir::Guard::If(self.lower_expr(cond))
496 let hir_id = self.next_id();
497 self.lower_attrs(hir_id, &arm.attrs);
502 body: self.lower_expr(&arm.body),
503 span: self.lower_span(arm.span),
507 /// Lower an `async` construct to a generator that is then wrapped so it implements `Future`.
512 /// std::future::from_generator(static move? |_task_context| -> <ret_ty> {
516 pub(super) fn make_async_expr(
518 capture_clause: CaptureBy,
519 closure_node_id: NodeId,
520 ret_ty: Option<AstP<Ty>>,
522 async_gen_kind: hir::AsyncGeneratorKind,
523 body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
524 ) -> hir::ExprKind<'hir> {
525 let output = match ret_ty {
526 Some(ty) => hir::FnRetTy::Return(self.lower_ty(&ty, ImplTraitContext::disallowed())),
527 None => hir::FnRetTy::DefaultReturn(self.lower_span(span)),
530 // Resume argument type. We let the compiler infer this to simplify the lowering. It is
531 // fully constrained by `future::from_generator`.
532 let input_ty = hir::Ty {
533 hir_id: self.next_id(),
534 kind: hir::TyKind::Infer,
535 span: self.lower_span(span),
538 // The closure/generator `FnDecl` takes a single (resume) argument of type `input_ty`.
539 let decl = self.arena.alloc(hir::FnDecl {
540 inputs: arena_vec![self; input_ty],
543 implicit_self: hir::ImplicitSelfKind::None,
546 // Lower the argument pattern/ident. The ident is used again in the `.await` lowering.
547 let (pat, task_context_hid) = self.pat_ident_binding_mode(
549 Ident::with_dummy_span(sym::_task_context),
550 hir::BindingAnnotation::Mutable,
552 let param = hir::Param {
553 hir_id: self.next_id(),
555 ty_span: self.lower_span(span),
556 span: self.lower_span(span),
558 let params = arena_vec![self; param];
560 let body_id = self.lower_body(move |this| {
561 this.generator_kind = Some(hir::GeneratorKind::Async(async_gen_kind));
563 let old_ctx = this.task_context;
564 this.task_context = Some(task_context_hid);
565 let res = body(this);
566 this.task_context = old_ctx;
570 // `static |_task_context| -> <ret_ty> { body }`:
571 let generator_kind = hir::ExprKind::Closure(
575 self.lower_span(span),
576 Some(hir::Movability::Static),
578 let generator = hir::Expr {
579 hir_id: self.lower_node_id(closure_node_id),
580 kind: generator_kind,
581 span: self.lower_span(span),
584 // `future::from_generator`:
586 self.mark_span_with_reason(DesugaringKind::Async, span, self.allow_gen_future.clone());
588 self.expr_lang_item_path(unstable_span, hir::LangItem::FromGenerator, ThinVec::new());
590 // `future::from_generator(generator)`:
591 hir::ExprKind::Call(self.arena.alloc(gen_future), arena_vec![self; generator])
594 /// Desugar `<expr>.await` into:
597 /// mut pinned => loop {
598 /// match unsafe { ::std::future::Future::poll(
599 /// <::std::pin::Pin>::new_unchecked(&mut pinned),
600 /// ::std::future::get_context(task_context),
602 /// ::std::task::Poll::Ready(result) => break result,
603 /// ::std::task::Poll::Pending => {}
605 /// task_context = yield ();
609 fn lower_expr_await(&mut self, await_span: Span, expr: &Expr) -> hir::ExprKind<'hir> {
610 match self.generator_kind {
611 Some(hir::GeneratorKind::Async(_)) => {}
612 Some(hir::GeneratorKind::Gen) | None => {
613 let mut err = struct_span_err!(
617 "`await` is only allowed inside `async` functions and blocks"
619 err.span_label(await_span, "only allowed inside `async` functions and blocks");
620 if let Some(item_sp) = self.current_item {
621 err.span_label(item_sp, "this is not `async`");
626 let span = self.mark_span_with_reason(DesugaringKind::Await, await_span, None);
627 let gen_future_span = self.mark_span_with_reason(
628 DesugaringKind::Await,
630 self.allow_gen_future.clone(),
632 let expr = self.lower_expr(expr);
634 let pinned_ident = Ident::with_dummy_span(sym::pinned);
635 let (pinned_pat, pinned_pat_hid) =
636 self.pat_ident_binding_mode(span, pinned_ident, hir::BindingAnnotation::Mutable);
638 let task_context_ident = Ident::with_dummy_span(sym::_task_context);
641 // ::std::future::Future::poll(
642 // ::std::pin::Pin::new_unchecked(&mut pinned),
643 // ::std::future::get_context(task_context),
647 let pinned = self.expr_ident(span, pinned_ident, pinned_pat_hid);
648 let ref_mut_pinned = self.expr_mut_addr_of(span, pinned);
649 let task_context = if let Some(task_context_hid) = self.task_context {
650 self.expr_ident_mut(span, task_context_ident, task_context_hid)
652 // Use of `await` outside of an async context, we cannot use `task_context` here.
655 let new_unchecked = self.expr_call_lang_item_fn_mut(
657 hir::LangItem::PinNewUnchecked,
658 arena_vec![self; ref_mut_pinned],
660 let get_context = self.expr_call_lang_item_fn_mut(
662 hir::LangItem::GetContext,
663 arena_vec![self; task_context],
665 let call = self.expr_call_lang_item_fn(
667 hir::LangItem::FuturePoll,
668 arena_vec![self; new_unchecked, get_context],
670 self.arena.alloc(self.expr_unsafe(call))
673 // `::std::task::Poll::Ready(result) => break result`
674 let loop_node_id = self.resolver.next_node_id();
675 let loop_hir_id = self.lower_node_id(loop_node_id);
677 let x_ident = Ident::with_dummy_span(sym::result);
678 let (x_pat, x_pat_hid) = self.pat_ident(span, x_ident);
679 let x_expr = self.expr_ident(span, x_ident, x_pat_hid);
680 let ready_field = self.single_pat_field(span, x_pat);
681 let ready_pat = self.pat_lang_item_variant(span, hir::LangItem::PollReady, ready_field);
682 let break_x = self.with_loop_scope(loop_node_id, move |this| {
684 hir::ExprKind::Break(this.lower_loop_destination(None), Some(x_expr));
685 this.arena.alloc(this.expr(await_span, expr_break, ThinVec::new()))
687 self.arm(ready_pat, break_x)
690 // `::std::task::Poll::Pending => {}`
692 let pending_pat = self.pat_lang_item_variant(span, hir::LangItem::PollPending, &[]);
693 let empty_block = self.expr_block_empty(span);
694 self.arm(pending_pat, empty_block)
697 let inner_match_stmt = {
698 let match_expr = self.expr_match(
701 arena_vec![self; ready_arm, pending_arm],
702 hir::MatchSource::AwaitDesugar,
704 self.stmt_expr(span, match_expr)
707 // task_context = yield ();
709 let unit = self.expr_unit(span);
710 let yield_expr = self.expr(
712 hir::ExprKind::Yield(unit, hir::YieldSource::Await { expr: Some(expr.hir_id) }),
715 let yield_expr = self.arena.alloc(yield_expr);
717 if let Some(task_context_hid) = self.task_context {
718 let lhs = self.expr_ident(span, task_context_ident, task_context_hid);
719 let assign = self.expr(
721 hir::ExprKind::Assign(lhs, yield_expr, self.lower_span(span)),
724 self.stmt_expr(span, assign)
726 // Use of `await` outside of an async context. Return `yield_expr` so that we can
727 // proceed with type checking.
728 self.stmt(span, hir::StmtKind::Semi(yield_expr))
732 let loop_block = self.block_all(span, arena_vec![self; inner_match_stmt, yield_stmt], None);
735 let loop_expr = self.arena.alloc(hir::Expr {
737 kind: hir::ExprKind::Loop(
740 hir::LoopSource::Loop,
741 self.lower_span(span),
743 span: self.lower_span(span),
746 // mut pinned => loop { ... }
747 let pinned_arm = self.arm(pinned_pat, loop_expr);
750 // mut pinned => loop { .. }
752 hir::ExprKind::Match(expr, arena_vec![self; pinned_arm], hir::MatchSource::AwaitDesugar)
755 fn lower_expr_closure(
757 capture_clause: CaptureBy,
758 movability: Movability,
762 ) -> hir::ExprKind<'hir> {
763 let (body_id, generator_option) = self.with_new_scopes(move |this| {
764 let prev = this.current_item;
765 this.current_item = Some(fn_decl_span);
766 let mut generator_kind = None;
767 let body_id = this.lower_fn_body(decl, |this| {
768 let e = this.lower_expr_mut(body);
769 generator_kind = this.generator_kind;
772 let generator_option =
773 this.generator_movability_for_fn(&decl, fn_decl_span, generator_kind, movability);
774 this.current_item = prev;
775 (body_id, generator_option)
778 // Lower outside new scope to preserve `is_in_loop_condition`.
779 let fn_decl = self.lower_fn_decl(decl, None, false, None);
781 hir::ExprKind::Closure(
785 self.lower_span(fn_decl_span),
790 fn generator_movability_for_fn(
794 generator_kind: Option<hir::GeneratorKind>,
795 movability: Movability,
796 ) -> Option<hir::Movability> {
797 match generator_kind {
798 Some(hir::GeneratorKind::Gen) => {
799 if decl.inputs.len() > 1 {
804 "too many parameters for a generator (expected 0 or 1 parameters)"
810 Some(hir::GeneratorKind::Async(_)) => {
811 panic!("non-`async` closure body turned `async` during lowering");
814 if movability == Movability::Static {
815 struct_span_err!(self.sess, fn_decl_span, E0697, "closures cannot be static")
823 fn lower_expr_async_closure(
825 capture_clause: CaptureBy,
830 ) -> hir::ExprKind<'hir> {
832 FnDecl { inputs: decl.inputs.clone(), output: FnRetTy::Default(fn_decl_span) };
834 let body_id = self.with_new_scopes(|this| {
835 // FIXME(cramertj): allow `async` non-`move` closures with arguments.
836 if capture_clause == CaptureBy::Ref && !decl.inputs.is_empty() {
841 "`async` non-`move` closures with parameters are not currently supported",
844 "consider using `let` statements to manually capture \
845 variables by reference before entering an `async move` closure",
850 // Transform `async |x: u8| -> X { ... }` into
851 // `|x: u8| future_from_generator(|| -> X { ... })`.
852 let body_id = this.lower_fn_body(&outer_decl, |this| {
854 if let FnRetTy::Ty(ty) = &decl.output { Some(ty.clone()) } else { None };
855 let async_body = this.make_async_expr(
860 hir::AsyncGeneratorKind::Closure,
861 |this| this.with_new_scopes(|this| this.lower_expr_mut(body)),
863 this.expr(fn_decl_span, async_body, ThinVec::new())
868 // We need to lower the declaration outside the new scope, because we
869 // have to conserve the state of being inside a loop condition for the
870 // closure argument types.
871 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
873 hir::ExprKind::Closure(
877 self.lower_span(fn_decl_span),
882 /// Destructure the LHS of complex assignments.
883 /// For instance, lower `(a, b) = t` to `{ let (lhs1, lhs2) = t; a = lhs1; b = lhs2; }`.
884 fn lower_expr_assign(
890 ) -> hir::ExprKind<'hir> {
891 // Return early in case of an ordinary assignment.
892 fn is_ordinary(lower_ctx: &mut LoweringContext<'_, '_>, lhs: &Expr) -> bool {
895 | ExprKind::Struct(..)
897 | ExprKind::Underscore => false,
898 // Check for tuple struct constructor.
899 ExprKind::Call(callee, ..) => lower_ctx.extract_tuple_struct_path(callee).is_none(),
900 ExprKind::Paren(e) => {
902 // We special-case `(..)` for consistency with patterns.
903 ExprKind::Range(None, None, RangeLimits::HalfOpen) => false,
904 _ => is_ordinary(lower_ctx, e),
910 if is_ordinary(self, lhs) {
911 return hir::ExprKind::Assign(
912 self.lower_expr(lhs),
913 self.lower_expr(rhs),
914 self.lower_span(eq_sign_span),
917 if !self.sess.features_untracked().destructuring_assignment {
919 &self.sess.parse_sess,
920 sym::destructuring_assignment,
922 "destructuring assignments are unstable",
924 .span_label(lhs.span, "cannot assign to this expression")
928 let mut assignments = vec![];
930 // The LHS becomes a pattern: `(lhs1, lhs2)`.
931 let pat = self.destructure_assign(lhs, eq_sign_span, &mut assignments);
932 let rhs = self.lower_expr(rhs);
934 // Introduce a `let` for destructuring: `let (lhs1, lhs2) = t`.
935 let destructure_let = self.stmt_let_pat(
940 hir::LocalSource::AssignDesugar(self.lower_span(eq_sign_span)),
943 // `a = lhs1; b = lhs2;`.
946 .alloc_from_iter(std::iter::once(destructure_let).chain(assignments.into_iter()));
948 // Wrap everything in a block.
949 hir::ExprKind::Block(&self.block_all(whole_span, stmts, None), None)
952 /// If the given expression is a path to a tuple struct, returns that path.
953 /// It is not a complete check, but just tries to reject most paths early
954 /// if they are not tuple structs.
955 /// Type checking will take care of the full validation later.
956 fn extract_tuple_struct_path<'a>(
959 ) -> Option<(&'a Option<QSelf>, &'a Path)> {
960 if let ExprKind::Path(qself, path) = &expr.kind {
961 // Does the path resolve to something disallowed in a tuple struct/variant pattern?
962 if let Some(partial_res) = self.resolver.get_partial_res(expr.id) {
963 if partial_res.unresolved_segments() == 0
964 && !partial_res.base_res().expected_in_tuple_struct_pat()
969 return Some((qself, path));
974 /// Convert the LHS of a destructuring assignment to a pattern.
975 /// Each sub-assignment is recorded in `assignments`.
976 fn destructure_assign(
980 assignments: &mut Vec<hir::Stmt<'hir>>,
981 ) -> &'hir hir::Pat<'hir> {
982 self.arena.alloc(self.destructure_assign_mut(lhs, eq_sign_span, assignments))
985 fn destructure_assign_mut(
989 assignments: &mut Vec<hir::Stmt<'hir>>,
990 ) -> hir::Pat<'hir> {
992 // Underscore pattern.
993 ExprKind::Underscore => {
994 return self.pat_without_dbm(lhs.span, hir::PatKind::Wild);
997 ExprKind::Array(elements) => {
999 self.destructure_sequence(elements, "slice", eq_sign_span, assignments);
1000 let slice_pat = if let Some((i, span)) = rest {
1001 let (before, after) = pats.split_at(i);
1002 hir::PatKind::Slice(
1004 Some(self.arena.alloc(self.pat_without_dbm(span, hir::PatKind::Wild))),
1008 hir::PatKind::Slice(pats, None, &[])
1010 return self.pat_without_dbm(lhs.span, slice_pat);
1013 ExprKind::Call(callee, args) => {
1014 if let Some((qself, path)) = self.extract_tuple_struct_path(callee) {
1015 let (pats, rest) = self.destructure_sequence(
1017 "tuple struct or variant",
1021 let qpath = self.lower_qpath(
1025 ParamMode::Optional,
1026 ImplTraitContext::disallowed(),
1028 // Destructure like a tuple struct.
1029 let tuple_struct_pat =
1030 hir::PatKind::TupleStruct(qpath, pats, rest.map(|r| r.0));
1031 return self.pat_without_dbm(lhs.span, tuple_struct_pat);
1035 ExprKind::Struct(se) => {
1036 let field_pats = self.arena.alloc_from_iter(se.fields.iter().map(|f| {
1037 let pat = self.destructure_assign(&f.expr, eq_sign_span, assignments);
1039 hir_id: self.next_id(),
1040 ident: self.lower_ident(f.ident),
1042 is_shorthand: f.is_shorthand,
1043 span: self.lower_span(f.span),
1046 let qpath = self.lower_qpath(
1050 ParamMode::Optional,
1051 ImplTraitContext::disallowed(),
1053 let fields_omitted = match &se.rest {
1054 StructRest::Base(e) => {
1058 "functional record updates are not allowed in destructuring \
1063 "consider removing the trailing pattern",
1065 rustc_errors::Applicability::MachineApplicable,
1070 StructRest::Rest(_) => true,
1071 StructRest::None => false,
1073 let struct_pat = hir::PatKind::Struct(qpath, field_pats, fields_omitted);
1074 return self.pat_without_dbm(lhs.span, struct_pat);
1077 ExprKind::Tup(elements) => {
1079 self.destructure_sequence(elements, "tuple", eq_sign_span, assignments);
1080 let tuple_pat = hir::PatKind::Tuple(pats, rest.map(|r| r.0));
1081 return self.pat_without_dbm(lhs.span, tuple_pat);
1083 ExprKind::Paren(e) => {
1084 // We special-case `(..)` for consistency with patterns.
1085 if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
1086 let tuple_pat = hir::PatKind::Tuple(&[], Some(0));
1087 return self.pat_without_dbm(lhs.span, tuple_pat);
1089 return self.destructure_assign_mut(e, eq_sign_span, assignments);
1094 // Treat all other cases as normal lvalue.
1095 let ident = Ident::new(sym::lhs, self.lower_span(lhs.span));
1096 let (pat, binding) = self.pat_ident_mut(lhs.span, ident);
1097 let ident = self.expr_ident(lhs.span, ident, binding);
1099 hir::ExprKind::Assign(self.lower_expr(lhs), ident, self.lower_span(eq_sign_span));
1100 let expr = self.expr(lhs.span, assign, ThinVec::new());
1101 assignments.push(self.stmt_expr(lhs.span, expr));
1105 /// Destructure a sequence of expressions occurring on the LHS of an assignment.
1106 /// Such a sequence occurs in a tuple (struct)/slice.
1107 /// Return a sequence of corresponding patterns, and the index and the span of `..` if it
1109 /// Each sub-assignment is recorded in `assignments`.
1110 fn destructure_sequence(
1112 elements: &[AstP<Expr>],
1115 assignments: &mut Vec<hir::Stmt<'hir>>,
1116 ) -> (&'hir [hir::Pat<'hir>], Option<(usize, Span)>) {
1117 let mut rest = None;
1119 self.arena.alloc_from_iter(elements.iter().enumerate().filter_map(|(i, e)| {
1120 // Check for `..` pattern.
1121 if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
1122 if let Some((_, prev_span)) = rest {
1123 self.ban_extra_rest_pat(e.span, prev_span, ctx);
1125 rest = Some((i, e.span));
1129 Some(self.destructure_assign_mut(e, eq_sign_span, assignments))
1135 /// Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`.
1136 fn lower_expr_range_closed(&mut self, span: Span, e1: &Expr, e2: &Expr) -> hir::ExprKind<'hir> {
1137 let e1 = self.lower_expr_mut(e1);
1138 let e2 = self.lower_expr_mut(e2);
1139 let fn_path = hir::QPath::LangItem(hir::LangItem::RangeInclusiveNew, self.lower_span(span));
1141 self.arena.alloc(self.expr(span, hir::ExprKind::Path(fn_path), ThinVec::new()));
1142 hir::ExprKind::Call(fn_expr, arena_vec![self; e1, e2])
1145 fn lower_expr_range(
1151 ) -> hir::ExprKind<'hir> {
1152 use rustc_ast::RangeLimits::*;
1154 let lang_item = match (e1, e2, lims) {
1155 (None, None, HalfOpen) => hir::LangItem::RangeFull,
1156 (Some(..), None, HalfOpen) => hir::LangItem::RangeFrom,
1157 (None, Some(..), HalfOpen) => hir::LangItem::RangeTo,
1158 (Some(..), Some(..), HalfOpen) => hir::LangItem::Range,
1159 (None, Some(..), Closed) => hir::LangItem::RangeToInclusive,
1160 (Some(..), Some(..), Closed) => unreachable!(),
1161 (_, None, Closed) => self.diagnostic().span_fatal(span, "inclusive range with no end"),
1164 let fields = self.arena.alloc_from_iter(
1165 e1.iter().map(|e| ("start", e)).chain(e2.iter().map(|e| ("end", e))).map(|(s, e)| {
1166 let expr = self.lower_expr(&e);
1167 let ident = Ident::new(Symbol::intern(s), self.lower_span(e.span));
1168 self.expr_field(ident, expr, e.span)
1172 hir::ExprKind::Struct(
1173 self.arena.alloc(hir::QPath::LangItem(lang_item, self.lower_span(span))),
1179 fn lower_label(&self, opt_label: Option<Label>) -> Option<Label> {
1180 let label = opt_label?;
1181 Some(Label { ident: self.lower_ident(label.ident) })
1184 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
1185 let target_id = match destination {
1187 if let Some(loop_id) = self.resolver.get_label_res(id) {
1188 Ok(self.lower_node_id(loop_id))
1190 Err(hir::LoopIdError::UnresolvedLabel)
1195 .map(|id| Ok(self.lower_node_id(id)))
1196 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope)),
1198 let label = self.lower_label(destination.map(|(_, label)| label));
1199 hir::Destination { label, target_id }
1202 fn lower_jump_destination(&mut self, id: NodeId, opt_label: Option<Label>) -> hir::Destination {
1203 if self.is_in_loop_condition && opt_label.is_none() {
1206 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition),
1209 self.lower_loop_destination(opt_label.map(|label| (id, label)))
1213 fn with_catch_scope<T>(&mut self, catch_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1214 let old_scope = self.catch_scope.replace(catch_id);
1215 let result = f(self);
1216 self.catch_scope = old_scope;
1220 fn with_loop_scope<T>(&mut self, loop_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1221 // We're no longer in the base loop's condition; we're in another loop.
1222 let was_in_loop_condition = self.is_in_loop_condition;
1223 self.is_in_loop_condition = false;
1225 let old_scope = self.loop_scope.replace(loop_id);
1226 let result = f(self);
1227 self.loop_scope = old_scope;
1229 self.is_in_loop_condition = was_in_loop_condition;
1234 fn with_loop_condition_scope<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
1235 let was_in_loop_condition = self.is_in_loop_condition;
1236 self.is_in_loop_condition = true;
1238 let result = f(self);
1240 self.is_in_loop_condition = was_in_loop_condition;
1245 fn lower_expr_llvm_asm(&mut self, asm: &LlvmInlineAsm) -> hir::ExprKind<'hir> {
1246 let inner = hir::LlvmInlineAsmInner {
1247 inputs: asm.inputs.iter().map(|&(c, _)| c).collect(),
1251 .map(|out| hir::LlvmInlineAsmOutput {
1252 constraint: out.constraint,
1254 is_indirect: out.is_indirect,
1255 span: self.lower_span(out.expr.span),
1259 asm_str_style: asm.asm_str_style,
1260 clobbers: asm.clobbers.clone(),
1261 volatile: asm.volatile,
1262 alignstack: asm.alignstack,
1263 dialect: asm.dialect,
1265 let hir_asm = hir::LlvmInlineAsm {
1267 inputs_exprs: self.arena.alloc_from_iter(
1268 asm.inputs.iter().map(|&(_, ref input)| self.lower_expr_mut(input)),
1272 .alloc_from_iter(asm.outputs.iter().map(|out| self.lower_expr_mut(&out.expr))),
1274 hir::ExprKind::LlvmInlineAsm(self.arena.alloc(hir_asm))
1277 fn lower_expr_field(&mut self, f: &ExprField) -> hir::ExprField<'hir> {
1279 hir_id: self.next_id(),
1280 ident: self.lower_ident(f.ident),
1281 expr: self.lower_expr(&f.expr),
1282 span: self.lower_span(f.span),
1283 is_shorthand: f.is_shorthand,
1287 fn lower_expr_yield(&mut self, span: Span, opt_expr: Option<&Expr>) -> hir::ExprKind<'hir> {
1288 match self.generator_kind {
1289 Some(hir::GeneratorKind::Gen) => {}
1290 Some(hir::GeneratorKind::Async(_)) => {
1295 "`async` generators are not yet supported"
1299 None => self.generator_kind = Some(hir::GeneratorKind::Gen),
1303 opt_expr.as_ref().map(|x| self.lower_expr(x)).unwrap_or_else(|| self.expr_unit(span));
1305 hir::ExprKind::Yield(expr, hir::YieldSource::Yield)
1308 /// Desugar `ExprForLoop` from: `[opt_ident]: for <pat> in <head> <body>` into:
1311 /// let result = match ::std::iter::IntoIterator::into_iter(<head>) {
1313 /// [opt_ident]: loop {
1315 /// match ::std::iter::Iterator::next(&mut iter) {
1316 /// ::std::option::Option::Some(val) => __next = val,
1317 /// ::std::option::Option::None => break
1319 /// let <pat> = __next;
1320 /// StmtKind::Expr(<body>);
1333 opt_label: Option<Label>,
1334 ) -> hir::Expr<'hir> {
1335 let orig_head_span = head.span;
1337 let mut head = self.lower_expr_mut(head);
1338 let desugared_span = self.mark_span_with_reason(
1339 DesugaringKind::ForLoop(ForLoopLoc::Head),
1343 head.span = self.lower_span(desugared_span);
1345 let iter = Ident::with_dummy_span(sym::iter);
1347 let next_ident = Ident::with_dummy_span(sym::__next);
1348 let (next_pat, next_pat_hid) = self.pat_ident_binding_mode(
1351 hir::BindingAnnotation::Mutable,
1354 // `::std::option::Option::Some(val) => __next = val`
1356 let val_ident = Ident::with_dummy_span(sym::val);
1357 let (val_pat, val_pat_hid) = self.pat_ident(pat.span, val_ident);
1358 let val_expr = self.expr_ident(pat.span, val_ident, val_pat_hid);
1359 let next_expr = self.expr_ident(pat.span, next_ident, next_pat_hid);
1360 let assign = self.arena.alloc(self.expr(
1362 hir::ExprKind::Assign(next_expr, val_expr, self.lower_span(pat.span)),
1365 let some_pat = self.pat_some(pat.span, val_pat);
1366 self.arm(some_pat, assign)
1369 // `::std::option::Option::None => break`
1372 self.with_loop_scope(e.id, |this| this.expr_break_alloc(e.span, ThinVec::new()));
1373 let pat = self.pat_none(e.span);
1374 self.arm(pat, break_expr)
1378 let (iter_pat, iter_pat_nid) =
1379 self.pat_ident_binding_mode(desugared_span, iter, hir::BindingAnnotation::Mutable);
1381 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
1383 let iter = self.expr_ident(desugared_span, iter, iter_pat_nid);
1384 let ref_mut_iter = self.expr_mut_addr_of(desugared_span, iter);
1385 let next_expr = self.expr_call_lang_item_fn(
1387 hir::LangItem::IteratorNext,
1388 arena_vec![self; ref_mut_iter],
1390 let arms = arena_vec![self; pat_arm, break_arm];
1392 self.expr_match(desugared_span, next_expr, arms, hir::MatchSource::ForLoopDesugar)
1394 let match_stmt = self.stmt_expr(desugared_span, match_expr);
1396 let next_expr = self.expr_ident(desugared_span, next_ident, next_pat_hid);
1399 let next_let = self.stmt_let_pat(
1404 hir::LocalSource::ForLoopDesugar,
1407 // `let <pat> = __next`
1408 let pat = self.lower_pat(pat);
1409 let pat_let = self.stmt_let_pat(
1414 hir::LocalSource::ForLoopDesugar,
1417 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
1418 let body_expr = self.expr_block(body_block, ThinVec::new());
1419 let body_stmt = self.stmt_expr(body.span, body_expr);
1421 let loop_block = self.block_all(
1423 arena_vec![self; next_let, match_stmt, pat_let, body_stmt],
1427 // `[opt_ident]: loop { ... }`
1428 let kind = hir::ExprKind::Loop(
1430 self.lower_label(opt_label),
1431 hir::LoopSource::ForLoop,
1432 self.lower_span(e.span.with_hi(orig_head_span.hi())),
1434 let loop_expr = self.arena.alloc(hir::Expr {
1435 hir_id: self.lower_node_id(e.id),
1437 span: self.lower_span(e.span),
1440 // `mut iter => { ... }`
1441 let iter_arm = self.arm(iter_pat, loop_expr);
1443 let into_iter_span = self.mark_span_with_reason(
1444 DesugaringKind::ForLoop(ForLoopLoc::IntoIter),
1449 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
1450 let into_iter_expr = {
1451 self.expr_call_lang_item_fn(
1453 hir::LangItem::IntoIterIntoIter,
1454 arena_vec![self; head],
1458 // #82462: to correctly diagnose borrow errors, the block that contains
1459 // the iter expr needs to have a span that covers the loop body.
1460 let desugared_full_span =
1461 self.mark_span_with_reason(DesugaringKind::ForLoop(ForLoopLoc::Head), e.span, None);
1463 let match_expr = self.arena.alloc(self.expr_match(
1464 desugared_full_span,
1466 arena_vec![self; iter_arm],
1467 hir::MatchSource::ForLoopDesugar,
1470 let attrs: Vec<_> = e.attrs.iter().map(|a| self.lower_attr(a)).collect();
1472 // This is effectively `{ let _result = ...; _result }`.
1473 // The construct was introduced in #21984 and is necessary to make sure that
1474 // temporaries in the `head` expression are dropped and do not leak to the
1475 // surrounding scope of the `match` since the `match` is not a terminating scope.
1477 // Also, add the attributes to the outer returned expr node.
1478 self.expr_drop_temps_mut(desugared_full_span, match_expr, attrs.into())
1481 /// Desugar `ExprKind::Try` from: `<expr>?` into:
1483 /// match Try::branch(<expr>) {
1484 /// ControlFlow::Continue(val) => #[allow(unreachable_code)] val,,
1485 /// ControlFlow::Break(residual) =>
1486 /// #[allow(unreachable_code)]
1487 /// // If there is an enclosing `try {...}`:
1488 /// break 'catch_target Try::from_residual(residual),
1490 /// return Try::from_residual(residual),
1493 fn lower_expr_try(&mut self, span: Span, sub_expr: &Expr) -> hir::ExprKind<'hir> {
1494 let unstable_span = self.mark_span_with_reason(
1495 DesugaringKind::QuestionMark,
1497 self.allow_try_trait.clone(),
1499 let try_span = self.sess.source_map().end_point(span);
1500 let try_span = self.mark_span_with_reason(
1501 DesugaringKind::QuestionMark,
1503 self.allow_try_trait.clone(),
1506 // `Try::branch(<expr>)`
1509 let sub_expr = self.lower_expr_mut(sub_expr);
1511 self.expr_call_lang_item_fn(
1513 hir::LangItem::TryTraitBranch,
1514 arena_vec![self; sub_expr],
1518 // `#[allow(unreachable_code)]`
1520 // `allow(unreachable_code)`
1522 let allow_ident = Ident::new(sym::allow, self.lower_span(span));
1523 let uc_ident = Ident::new(sym::unreachable_code, self.lower_span(span));
1524 let uc_nested = attr::mk_nested_word_item(uc_ident);
1525 attr::mk_list_item(allow_ident, vec![uc_nested])
1527 attr::mk_attr_outer(allow)
1529 let attrs = vec![attr];
1531 // `ControlFlow::Continue(val) => #[allow(unreachable_code)] val,`
1532 let continue_arm = {
1533 let val_ident = Ident::with_dummy_span(sym::val);
1534 let (val_pat, val_pat_nid) = self.pat_ident(span, val_ident);
1535 let val_expr = self.arena.alloc(self.expr_ident_with_attrs(
1539 ThinVec::from(attrs.clone()),
1541 let continue_pat = self.pat_cf_continue(unstable_span, val_pat);
1542 self.arm(continue_pat, val_expr)
1545 // `ControlFlow::Break(residual) =>
1546 // #[allow(unreachable_code)]
1547 // return Try::from_residual(residual),`
1549 let residual_ident = Ident::with_dummy_span(sym::residual);
1550 let (residual_local, residual_local_nid) = self.pat_ident(try_span, residual_ident);
1551 let residual_expr = self.expr_ident_mut(try_span, residual_ident, residual_local_nid);
1552 let from_residual_expr = self.wrap_in_try_constructor(
1553 hir::LangItem::TryTraitFromResidual,
1555 self.arena.alloc(residual_expr),
1558 let thin_attrs = ThinVec::from(attrs);
1559 let ret_expr = if let Some(catch_node) = self.catch_scope {
1560 let target_id = Ok(self.lower_node_id(catch_node));
1561 self.arena.alloc(self.expr(
1563 hir::ExprKind::Break(
1564 hir::Destination { label: None, target_id },
1565 Some(from_residual_expr),
1570 self.arena.alloc(self.expr(
1572 hir::ExprKind::Ret(Some(from_residual_expr)),
1577 let break_pat = self.pat_cf_break(try_span, residual_local);
1578 self.arm(break_pat, ret_expr)
1581 hir::ExprKind::Match(
1583 arena_vec![self; break_arm, continue_arm],
1584 hir::MatchSource::TryDesugar,
1588 // =========================================================================
1589 // Helper methods for building HIR.
1590 // =========================================================================
1592 /// Wrap the given `expr` in a terminating scope using `hir::ExprKind::DropTemps`.
1594 /// In terms of drop order, it has the same effect as wrapping `expr` in
1595 /// `{ let _t = $expr; _t }` but should provide better compile-time performance.
1597 /// The drop order can be important in e.g. `if expr { .. }`.
1598 pub(super) fn expr_drop_temps(
1601 expr: &'hir hir::Expr<'hir>,
1603 ) -> &'hir hir::Expr<'hir> {
1604 self.arena.alloc(self.expr_drop_temps_mut(span, expr, attrs))
1607 pub(super) fn expr_drop_temps_mut(
1610 expr: &'hir hir::Expr<'hir>,
1612 ) -> hir::Expr<'hir> {
1613 self.expr(span, hir::ExprKind::DropTemps(expr), attrs)
1619 arg: &'hir hir::Expr<'hir>,
1620 arms: &'hir [hir::Arm<'hir>],
1621 source: hir::MatchSource,
1622 ) -> hir::Expr<'hir> {
1623 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
1626 fn expr_break(&mut self, span: Span, attrs: AttrVec) -> hir::Expr<'hir> {
1627 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
1628 self.expr(span, expr_break, attrs)
1631 fn expr_break_alloc(&mut self, span: Span, attrs: AttrVec) -> &'hir hir::Expr<'hir> {
1632 let expr_break = self.expr_break(span, attrs);
1633 self.arena.alloc(expr_break)
1636 fn expr_mut_addr_of(&mut self, span: Span, e: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
1639 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Mut, e),
1644 fn expr_unit(&mut self, sp: Span) -> &'hir hir::Expr<'hir> {
1645 self.arena.alloc(self.expr(sp, hir::ExprKind::Tup(&[]), ThinVec::new()))
1651 e: &'hir hir::Expr<'hir>,
1652 args: &'hir [hir::Expr<'hir>],
1653 ) -> hir::Expr<'hir> {
1654 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
1660 e: &'hir hir::Expr<'hir>,
1661 args: &'hir [hir::Expr<'hir>],
1662 ) -> &'hir hir::Expr<'hir> {
1663 self.arena.alloc(self.expr_call_mut(span, e, args))
1666 fn expr_call_lang_item_fn_mut(
1669 lang_item: hir::LangItem,
1670 args: &'hir [hir::Expr<'hir>],
1671 ) -> hir::Expr<'hir> {
1672 let path = self.arena.alloc(self.expr_lang_item_path(span, lang_item, ThinVec::new()));
1673 self.expr_call_mut(span, path, args)
1676 fn expr_call_lang_item_fn(
1679 lang_item: hir::LangItem,
1680 args: &'hir [hir::Expr<'hir>],
1681 ) -> &'hir hir::Expr<'hir> {
1682 self.arena.alloc(self.expr_call_lang_item_fn_mut(span, lang_item, args))
1685 fn expr_lang_item_path(
1688 lang_item: hir::LangItem,
1690 ) -> hir::Expr<'hir> {
1693 hir::ExprKind::Path(hir::QPath::LangItem(lang_item, self.lower_span(span))),
1698 pub(super) fn expr_ident(
1702 binding: hir::HirId,
1703 ) -> &'hir hir::Expr<'hir> {
1704 self.arena.alloc(self.expr_ident_mut(sp, ident, binding))
1707 pub(super) fn expr_ident_mut(
1711 binding: hir::HirId,
1712 ) -> hir::Expr<'hir> {
1713 self.expr_ident_with_attrs(sp, ident, binding, ThinVec::new())
1716 fn expr_ident_with_attrs(
1720 binding: hir::HirId,
1722 ) -> hir::Expr<'hir> {
1723 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
1725 self.arena.alloc(hir::Path {
1726 span: self.lower_span(span),
1727 res: Res::Local(binding),
1728 segments: arena_vec![self; hir::PathSegment::from_ident(ident)],
1732 self.expr(span, expr_path, attrs)
1735 fn expr_unsafe(&mut self, expr: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
1736 let hir_id = self.next_id();
1737 let span = expr.span;
1740 hir::ExprKind::Block(
1741 self.arena.alloc(hir::Block {
1745 rules: hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::CompilerGenerated),
1746 span: self.lower_span(span),
1747 targeted_by_break: false,
1755 fn expr_block_empty(&mut self, span: Span) -> &'hir hir::Expr<'hir> {
1756 let blk = self.block_all(span, &[], None);
1757 let expr = self.expr_block(blk, ThinVec::new());
1758 self.arena.alloc(expr)
1761 pub(super) fn expr_block(
1763 b: &'hir hir::Block<'hir>,
1765 ) -> hir::Expr<'hir> {
1766 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
1772 kind: hir::ExprKind<'hir>,
1774 ) -> hir::Expr<'hir> {
1775 let hir_id = self.next_id();
1776 self.lower_attrs(hir_id, &attrs);
1777 hir::Expr { hir_id, kind, span: self.lower_span(span) }
1783 expr: &'hir hir::Expr<'hir>,
1785 ) -> hir::ExprField<'hir> {
1787 hir_id: self.next_id(),
1789 span: self.lower_span(span),
1791 is_shorthand: false,
1795 fn arm(&mut self, pat: &'hir hir::Pat<'hir>, expr: &'hir hir::Expr<'hir>) -> hir::Arm<'hir> {
1797 hir_id: self.next_id(),
1800 span: self.lower_span(expr.span),