1 use super::{ImplTraitContext, LoweringContext, ParamMode, ParenthesizedGenericArgs};
4 use rustc_ast::ptr::P as AstP;
6 use rustc_data_structures::fx::FxHashMap;
7 use rustc_data_structures::stack::ensure_sufficient_stack;
8 use rustc_data_structures::thin_vec::ThinVec;
9 use rustc_errors::struct_span_err;
11 use rustc_hir::def::Res;
12 use rustc_session::parse::feature_err;
13 use rustc_span::hygiene::ForLoopLoc;
14 use rustc_span::source_map::{respan, DesugaringKind, Span, Spanned};
15 use rustc_span::symbol::{sym, Ident, Symbol};
16 use rustc_target::asm;
17 use std::collections::hash_map::Entry;
20 impl<'hir> LoweringContext<'_, 'hir> {
21 fn lower_exprs(&mut self, exprs: &[AstP<Expr>]) -> &'hir [hir::Expr<'hir>] {
22 self.arena.alloc_from_iter(exprs.iter().map(|x| self.lower_expr_mut(x)))
25 pub(super) fn lower_expr(&mut self, e: &Expr) -> &'hir hir::Expr<'hir> {
26 self.arena.alloc(self.lower_expr_mut(e))
29 pub(super) fn lower_expr_mut(&mut self, e: &Expr) -> hir::Expr<'hir> {
30 ensure_sufficient_stack(|| {
31 let kind = match e.kind {
32 ExprKind::Box(ref inner) => hir::ExprKind::Box(self.lower_expr(inner)),
33 ExprKind::Array(ref exprs) => hir::ExprKind::Array(self.lower_exprs(exprs)),
34 ExprKind::ConstBlock(ref anon_const) => {
35 let anon_const = self.lower_anon_const(anon_const);
36 hir::ExprKind::ConstBlock(anon_const)
38 ExprKind::Repeat(ref expr, ref count) => {
39 let expr = self.lower_expr(expr);
40 let count = self.lower_anon_const(count);
41 hir::ExprKind::Repeat(expr, count)
43 ExprKind::Tup(ref elts) => hir::ExprKind::Tup(self.lower_exprs(elts)),
44 ExprKind::Call(ref f, ref args) => {
45 let f = self.lower_expr(f);
46 hir::ExprKind::Call(f, self.lower_exprs(args))
48 ExprKind::MethodCall(ref seg, ref args, span) => {
49 let hir_seg = self.arena.alloc(self.lower_path_segment(
54 ParenthesizedGenericArgs::Err,
55 ImplTraitContext::disallowed(),
58 let args = self.lower_exprs(args);
59 hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args, span)
61 ExprKind::Binary(binop, ref lhs, ref rhs) => {
62 let binop = self.lower_binop(binop);
63 let lhs = self.lower_expr(lhs);
64 let rhs = self.lower_expr(rhs);
65 hir::ExprKind::Binary(binop, lhs, rhs)
67 ExprKind::Unary(op, ref ohs) => {
68 let op = self.lower_unop(op);
69 let ohs = self.lower_expr(ohs);
70 hir::ExprKind::Unary(op, ohs)
72 ExprKind::Lit(ref l) => hir::ExprKind::Lit(respan(l.span, l.kind.clone())),
73 ExprKind::Cast(ref expr, ref ty) => {
74 let expr = self.lower_expr(expr);
75 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
76 hir::ExprKind::Cast(expr, ty)
78 ExprKind::Type(ref expr, ref ty) => {
79 let expr = self.lower_expr(expr);
80 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
81 hir::ExprKind::Type(expr, ty)
83 ExprKind::AddrOf(k, m, ref ohs) => {
84 let ohs = self.lower_expr(ohs);
85 hir::ExprKind::AddrOf(k, m, ohs)
87 ExprKind::Let(ref pat, ref scrutinee) => {
88 self.lower_expr_let(e.span, pat, scrutinee)
90 ExprKind::If(ref cond, ref then, ref else_opt) => {
91 self.lower_expr_if(e.span, cond, then, else_opt.as_deref())
93 ExprKind::While(ref cond, ref body, opt_label) => self
94 .with_loop_scope(e.id, |this| {
95 this.lower_expr_while_in_loop_scope(e.span, cond, body, opt_label)
97 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
99 this.lower_block(body, false),
101 hir::LoopSource::Loop,
104 ExprKind::TryBlock(ref body) => self.lower_expr_try_block(body),
105 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
106 self.lower_expr(expr),
107 self.arena.alloc_from_iter(arms.iter().map(|x| self.lower_arm(x))),
108 hir::MatchSource::Normal,
110 ExprKind::Async(capture_clause, closure_node_id, ref block) => self
116 hir::AsyncGeneratorKind::Block,
117 |this| this.with_new_scopes(|this| this.lower_block_expr(block)),
119 ExprKind::Await(ref expr) => self.lower_expr_await(e.span, expr),
128 if let Async::Yes { closure_id, .. } = asyncness {
129 self.lower_expr_async_closure(
137 self.lower_expr_closure(
146 ExprKind::Block(ref blk, opt_label) => {
147 hir::ExprKind::Block(self.lower_block(blk, opt_label.is_some()), opt_label)
149 ExprKind::Assign(ref el, ref er, span) => {
150 self.lower_expr_assign(el, er, span, e.span)
152 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
153 self.lower_binop(op),
157 ExprKind::Field(ref el, ident) => hir::ExprKind::Field(self.lower_expr(el), ident),
158 ExprKind::Index(ref el, ref er) => {
159 hir::ExprKind::Index(self.lower_expr(el), self.lower_expr(er))
161 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
162 self.lower_expr_range_closed(e.span, e1, e2)
164 ExprKind::Range(ref e1, ref e2, lims) => {
165 self.lower_expr_range(e.span, e1.as_deref(), e2.as_deref(), lims)
167 ExprKind::Path(ref qself, ref path) => {
168 let qpath = self.lower_qpath(
173 ImplTraitContext::disallowed(),
175 hir::ExprKind::Path(qpath)
177 ExprKind::Break(opt_label, ref opt_expr) => {
178 let opt_expr = opt_expr.as_ref().map(|x| self.lower_expr(x));
179 hir::ExprKind::Break(self.lower_jump_destination(e.id, opt_label), opt_expr)
181 ExprKind::Continue(opt_label) => {
182 hir::ExprKind::Continue(self.lower_jump_destination(e.id, opt_label))
184 ExprKind::Ret(ref e) => {
185 let e = e.as_ref().map(|x| self.lower_expr(x));
186 hir::ExprKind::Ret(e)
188 ExprKind::InlineAsm(ref asm) => self.lower_expr_asm(e.span, asm),
189 ExprKind::LlvmInlineAsm(ref asm) => self.lower_expr_llvm_asm(asm),
190 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => {
191 let maybe_expr = maybe_expr.as_ref().map(|x| self.lower_expr(x));
192 hir::ExprKind::Struct(
193 self.arena.alloc(self.lower_qpath(
198 ImplTraitContext::disallowed(),
200 self.arena.alloc_from_iter(fields.iter().map(|x| self.lower_field(x))),
204 ExprKind::Yield(ref opt_expr) => self.lower_expr_yield(e.span, opt_expr.as_deref()),
205 ExprKind::Err => hir::ExprKind::Err,
206 ExprKind::Try(ref sub_expr) => self.lower_expr_try(e.span, sub_expr),
207 ExprKind::Paren(ref ex) => {
208 let mut ex = self.lower_expr_mut(ex);
209 // Include parens in span, but only if it is a super-span.
210 if e.span.contains(ex.span) {
213 // Merge attributes into the inner expression.
214 let mut attrs: Vec<_> = e.attrs.iter().map(|a| self.lower_attr(a)).collect();
215 attrs.extend::<Vec<_>>(ex.attrs.into());
216 ex.attrs = attrs.into();
220 // Desugar `ExprForLoop`
221 // from: `[opt_ident]: for <pat> in <head> <body>`
222 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
223 return self.lower_expr_for(e, pat, head, body, opt_label);
225 ExprKind::MacCall(_) => panic!("{:?} shouldn't exist here", e.span),
229 hir_id: self.lower_node_id(e.id),
232 attrs: e.attrs.iter().map(|a| self.lower_attr(a)).collect::<Vec<_>>().into(),
237 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
239 UnOp::Deref => hir::UnOp::UnDeref,
240 UnOp::Not => hir::UnOp::UnNot,
241 UnOp::Neg => hir::UnOp::UnNeg,
245 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
248 BinOpKind::Add => hir::BinOpKind::Add,
249 BinOpKind::Sub => hir::BinOpKind::Sub,
250 BinOpKind::Mul => hir::BinOpKind::Mul,
251 BinOpKind::Div => hir::BinOpKind::Div,
252 BinOpKind::Rem => hir::BinOpKind::Rem,
253 BinOpKind::And => hir::BinOpKind::And,
254 BinOpKind::Or => hir::BinOpKind::Or,
255 BinOpKind::BitXor => hir::BinOpKind::BitXor,
256 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
257 BinOpKind::BitOr => hir::BinOpKind::BitOr,
258 BinOpKind::Shl => hir::BinOpKind::Shl,
259 BinOpKind::Shr => hir::BinOpKind::Shr,
260 BinOpKind::Eq => hir::BinOpKind::Eq,
261 BinOpKind::Lt => hir::BinOpKind::Lt,
262 BinOpKind::Le => hir::BinOpKind::Le,
263 BinOpKind::Ne => hir::BinOpKind::Ne,
264 BinOpKind::Ge => hir::BinOpKind::Ge,
265 BinOpKind::Gt => hir::BinOpKind::Gt,
271 /// Emit an error and lower `ast::ExprKind::Let(pat, scrutinee)` into:
273 /// match scrutinee { pats => true, _ => false }
275 fn lower_expr_let(&mut self, span: Span, pat: &Pat, scrutinee: &Expr) -> hir::ExprKind<'hir> {
276 // If we got here, the `let` expression is not allowed.
278 if self.sess.opts.unstable_features.is_nightly_build() {
280 .struct_span_err(span, "`let` expressions are not supported here")
281 .note("only supported directly in conditions of `if`- and `while`-expressions")
282 .note("as well as when nested within `&&` and parenthesis in those conditions")
286 .struct_span_err(span, "expected expression, found statement (`let`)")
287 .note("variable declaration using `let` is a statement")
291 // For better recovery, we emit:
293 // match scrutinee { pat => true, _ => false }
295 // While this doesn't fully match the user's intent, it has key advantages:
296 // 1. We can avoid using `abort_if_errors`.
297 // 2. We can typeck both `pat` and `scrutinee`.
298 // 3. `pat` is allowed to be refutable.
299 // 4. The return type of the block is `bool` which seems like what the user wanted.
300 let scrutinee = self.lower_expr(scrutinee);
302 let pat = self.lower_pat(pat);
303 let expr = self.expr_bool(span, true);
307 let pat = self.pat_wild(span);
308 let expr = self.expr_bool(span, false);
311 hir::ExprKind::Match(
313 arena_vec![self; then_arm, else_arm],
314 hir::MatchSource::Normal,
323 else_opt: Option<&Expr>,
324 ) -> hir::ExprKind<'hir> {
325 // FIXME(#53667): handle lowering of && and parens.
327 // `_ => else_block` where `else_block` is `{}` if there's `None`:
328 let else_pat = self.pat_wild(span);
329 let (else_expr, contains_else_clause) = match else_opt {
330 None => (self.expr_block_empty(span), false),
331 Some(els) => (self.lower_expr(els), true),
333 let else_arm = self.arm(else_pat, else_expr);
335 // Handle then + scrutinee:
336 let then_expr = self.lower_block_expr(then);
337 let (then_pat, scrutinee, desugar) = match cond.kind {
338 // `<pat> => <then>`:
339 ExprKind::Let(ref pat, ref scrutinee) => {
340 let scrutinee = self.lower_expr(scrutinee);
341 let pat = self.lower_pat(pat);
342 (pat, scrutinee, hir::MatchSource::IfLetDesugar { contains_else_clause })
347 let cond = self.lower_expr(cond);
349 self.mark_span_with_reason(DesugaringKind::CondTemporary, cond.span, None);
350 // Wrap in a construct equivalent to `{ let _t = $cond; _t }`
351 // to preserve drop semantics since `if cond { ... }` does not
352 // let temporaries live outside of `cond`.
353 let cond = self.expr_drop_temps(span_block, cond, ThinVec::new());
354 let pat = self.pat_bool(span, true);
355 (pat, cond, hir::MatchSource::IfDesugar { contains_else_clause })
358 let then_arm = self.arm(then_pat, self.arena.alloc(then_expr));
360 hir::ExprKind::Match(scrutinee, arena_vec![self; then_arm, else_arm], desugar)
363 fn lower_expr_while_in_loop_scope(
368 opt_label: Option<Label>,
369 ) -> hir::ExprKind<'hir> {
370 // FIXME(#53667): handle lowering of && and parens.
372 // Note that the block AND the condition are evaluated in the loop scope.
373 // This is done to allow `break` from inside the condition of the loop.
377 let else_pat = self.pat_wild(span);
378 let else_expr = self.expr_break(span, ThinVec::new());
379 self.arm(else_pat, else_expr)
382 // Handle then + scrutinee:
383 let then_expr = self.lower_block_expr(body);
384 let (then_pat, scrutinee, desugar, source) = match cond.kind {
385 ExprKind::Let(ref pat, ref scrutinee) => {
388 // [opt_ident]: loop {
389 // match <sub_expr> {
394 let scrutinee = self.with_loop_condition_scope(|t| t.lower_expr(scrutinee));
395 let pat = self.lower_pat(pat);
396 (pat, scrutinee, hir::MatchSource::WhileLetDesugar, hir::LoopSource::WhileLet)
399 // We desugar: `'label: while $cond $body` into:
403 // match drop-temps { $cond } {
411 let cond = self.with_loop_condition_scope(|this| this.lower_expr(cond));
413 self.mark_span_with_reason(DesugaringKind::CondTemporary, cond.span, None);
414 // Wrap in a construct equivalent to `{ let _t = $cond; _t }`
415 // to preserve drop semantics since `while cond { ... }` does not
416 // let temporaries live outside of `cond`.
417 let cond = self.expr_drop_temps(span_block, cond, ThinVec::new());
419 let pat = self.pat_bool(span, true);
420 (pat, cond, hir::MatchSource::WhileDesugar, hir::LoopSource::While)
423 let then_arm = self.arm(then_pat, self.arena.alloc(then_expr));
425 // `match <scrutinee> { ... }`
427 self.expr_match(span, scrutinee, arena_vec![self; then_arm, else_arm], desugar);
429 // `[opt_ident]: loop { ... }`
430 hir::ExprKind::Loop(self.block_expr(self.arena.alloc(match_expr)), opt_label, source)
433 /// Desugar `try { <stmts>; <expr> }` into `{ <stmts>; ::std::ops::Try::from_ok(<expr>) }`,
434 /// `try { <stmts>; }` into `{ <stmts>; ::std::ops::Try::from_ok(()) }`
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_ok($tail_expr)`
464 block.expr = Some(this.wrap_in_try_constructor(
465 hir::LangItem::TryFromOk,
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> {
489 hir_id: self.next_id(),
490 attrs: self.lower_attrs(&arm.attrs),
491 pat: self.lower_pat(&arm.pat),
492 guard: match arm.guard {
493 Some(ref x) => Some(hir::Guard::If(self.lower_expr(x))),
496 body: self.lower_expr(&arm.body),
501 /// Lower an `async` construct to a generator that is then wrapped so it implements `Future`.
506 /// std::future::from_generator(static move? |_task_context| -> <ret_ty> {
510 pub(super) fn make_async_expr(
512 capture_clause: CaptureBy,
513 closure_node_id: NodeId,
514 ret_ty: Option<AstP<Ty>>,
516 async_gen_kind: hir::AsyncGeneratorKind,
517 body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
518 ) -> hir::ExprKind<'hir> {
519 let output = match ret_ty {
520 Some(ty) => hir::FnRetTy::Return(self.lower_ty(&ty, ImplTraitContext::disallowed())),
521 None => hir::FnRetTy::DefaultReturn(span),
524 // Resume argument type. We let the compiler infer this to simplify the lowering. It is
525 // fully constrained by `future::from_generator`.
526 let input_ty = hir::Ty { hir_id: self.next_id(), kind: hir::TyKind::Infer, span };
528 // The closure/generator `FnDecl` takes a single (resume) argument of type `input_ty`.
529 let decl = self.arena.alloc(hir::FnDecl {
530 inputs: arena_vec![self; input_ty],
533 implicit_self: hir::ImplicitSelfKind::None,
536 // Lower the argument pattern/ident. The ident is used again in the `.await` lowering.
537 let (pat, task_context_hid) = self.pat_ident_binding_mode(
539 Ident::with_dummy_span(sym::_task_context),
540 hir::BindingAnnotation::Mutable,
542 let param = hir::Param { attrs: &[], hir_id: self.next_id(), pat, ty_span: span, span };
543 let params = arena_vec![self; param];
545 let body_id = self.lower_body(move |this| {
546 this.generator_kind = Some(hir::GeneratorKind::Async(async_gen_kind));
548 let old_ctx = this.task_context;
549 this.task_context = Some(task_context_hid);
550 let res = body(this);
551 this.task_context = old_ctx;
555 // `static |_task_context| -> <ret_ty> { body }`:
556 let generator_kind = hir::ExprKind::Closure(
561 Some(hir::Movability::Static),
563 let generator = hir::Expr {
564 hir_id: self.lower_node_id(closure_node_id),
565 kind: generator_kind,
567 attrs: ThinVec::new(),
570 // `future::from_generator`:
572 self.mark_span_with_reason(DesugaringKind::Async, span, self.allow_gen_future.clone());
574 self.expr_lang_item_path(unstable_span, hir::LangItem::FromGenerator, ThinVec::new());
576 // `future::from_generator(generator)`:
577 hir::ExprKind::Call(self.arena.alloc(gen_future), arena_vec![self; generator])
580 /// Desugar `<expr>.await` into:
583 /// mut pinned => loop {
584 /// match unsafe { ::std::future::Future::poll(
585 /// <::std::pin::Pin>::new_unchecked(&mut pinned),
586 /// ::std::future::get_context(task_context),
588 /// ::std::task::Poll::Ready(result) => break result,
589 /// ::std::task::Poll::Pending => {}
591 /// task_context = yield ();
595 fn lower_expr_await(&mut self, await_span: Span, expr: &Expr) -> hir::ExprKind<'hir> {
596 match self.generator_kind {
597 Some(hir::GeneratorKind::Async(_)) => {}
598 Some(hir::GeneratorKind::Gen) | None => {
599 let mut err = struct_span_err!(
603 "`await` is only allowed inside `async` functions and blocks"
605 err.span_label(await_span, "only allowed inside `async` functions and blocks");
606 if let Some(item_sp) = self.current_item {
607 err.span_label(item_sp, "this is not `async`");
612 let span = self.mark_span_with_reason(DesugaringKind::Await, await_span, None);
613 let gen_future_span = self.mark_span_with_reason(
614 DesugaringKind::Await,
616 self.allow_gen_future.clone(),
618 let expr = self.lower_expr(expr);
620 let pinned_ident = Ident::with_dummy_span(sym::pinned);
621 let (pinned_pat, pinned_pat_hid) =
622 self.pat_ident_binding_mode(span, pinned_ident, hir::BindingAnnotation::Mutable);
624 let task_context_ident = Ident::with_dummy_span(sym::_task_context);
627 // ::std::future::Future::poll(
628 // ::std::pin::Pin::new_unchecked(&mut pinned),
629 // ::std::future::get_context(task_context),
633 let pinned = self.expr_ident(span, pinned_ident, pinned_pat_hid);
634 let ref_mut_pinned = self.expr_mut_addr_of(span, pinned);
635 let task_context = if let Some(task_context_hid) = self.task_context {
636 self.expr_ident_mut(span, task_context_ident, task_context_hid)
638 // Use of `await` outside of an async context, we cannot use `task_context` here.
641 let new_unchecked = self.expr_call_lang_item_fn_mut(
643 hir::LangItem::PinNewUnchecked,
644 arena_vec![self; ref_mut_pinned],
646 let get_context = self.expr_call_lang_item_fn_mut(
648 hir::LangItem::GetContext,
649 arena_vec![self; task_context],
651 let call = self.expr_call_lang_item_fn(
653 hir::LangItem::FuturePoll,
654 arena_vec![self; new_unchecked, get_context],
656 self.arena.alloc(self.expr_unsafe(call))
659 // `::std::task::Poll::Ready(result) => break result`
660 let loop_node_id = self.resolver.next_node_id();
661 let loop_hir_id = self.lower_node_id(loop_node_id);
663 let x_ident = Ident::with_dummy_span(sym::result);
664 let (x_pat, x_pat_hid) = self.pat_ident(span, x_ident);
665 let x_expr = self.expr_ident(span, x_ident, x_pat_hid);
666 let ready_field = self.single_pat_field(span, x_pat);
667 let ready_pat = self.pat_lang_item_variant(span, hir::LangItem::PollReady, ready_field);
668 let break_x = self.with_loop_scope(loop_node_id, move |this| {
670 hir::ExprKind::Break(this.lower_loop_destination(None), Some(x_expr));
671 this.arena.alloc(this.expr(await_span, expr_break, ThinVec::new()))
673 self.arm(ready_pat, break_x)
676 // `::std::task::Poll::Pending => {}`
678 let pending_pat = self.pat_lang_item_variant(span, hir::LangItem::PollPending, &[]);
679 let empty_block = self.expr_block_empty(span);
680 self.arm(pending_pat, empty_block)
683 let inner_match_stmt = {
684 let match_expr = self.expr_match(
687 arena_vec![self; ready_arm, pending_arm],
688 hir::MatchSource::AwaitDesugar,
690 self.stmt_expr(span, match_expr)
693 // task_context = yield ();
695 let unit = self.expr_unit(span);
696 let yield_expr = self.expr(
698 hir::ExprKind::Yield(unit, hir::YieldSource::Await { expr: Some(expr.hir_id) }),
701 let yield_expr = self.arena.alloc(yield_expr);
703 if let Some(task_context_hid) = self.task_context {
704 let lhs = self.expr_ident(span, task_context_ident, task_context_hid);
706 self.expr(span, hir::ExprKind::Assign(lhs, yield_expr, span), AttrVec::new());
707 self.stmt_expr(span, assign)
709 // Use of `await` outside of an async context. Return `yield_expr` so that we can
710 // proceed with type checking.
711 self.stmt(span, hir::StmtKind::Semi(yield_expr))
715 let loop_block = self.block_all(span, arena_vec![self; inner_match_stmt, yield_stmt], None);
718 let loop_expr = self.arena.alloc(hir::Expr {
720 kind: hir::ExprKind::Loop(loop_block, None, hir::LoopSource::Loop),
722 attrs: ThinVec::new(),
725 // mut pinned => loop { ... }
726 let pinned_arm = self.arm(pinned_pat, loop_expr);
729 // mut pinned => loop { .. }
731 hir::ExprKind::Match(expr, arena_vec![self; pinned_arm], hir::MatchSource::AwaitDesugar)
734 fn lower_expr_closure(
736 capture_clause: CaptureBy,
737 movability: Movability,
741 ) -> hir::ExprKind<'hir> {
742 // Lower outside new scope to preserve `is_in_loop_condition`.
743 let fn_decl = self.lower_fn_decl(decl, None, false, None);
745 self.with_new_scopes(move |this| {
746 let prev = this.current_item;
747 this.current_item = Some(fn_decl_span);
748 let mut generator_kind = None;
749 let body_id = this.lower_fn_body(decl, |this| {
750 let e = this.lower_expr_mut(body);
751 generator_kind = this.generator_kind;
754 let generator_option =
755 this.generator_movability_for_fn(&decl, fn_decl_span, generator_kind, movability);
756 this.current_item = prev;
757 hir::ExprKind::Closure(capture_clause, fn_decl, body_id, fn_decl_span, generator_option)
761 fn generator_movability_for_fn(
765 generator_kind: Option<hir::GeneratorKind>,
766 movability: Movability,
767 ) -> Option<hir::Movability> {
768 match generator_kind {
769 Some(hir::GeneratorKind::Gen) => {
770 if decl.inputs.len() > 1 {
775 "too many parameters for a generator (expected 0 or 1 parameters)"
781 Some(hir::GeneratorKind::Async(_)) => {
782 panic!("non-`async` closure body turned `async` during lowering");
785 if movability == Movability::Static {
786 struct_span_err!(self.sess, fn_decl_span, E0697, "closures cannot be static")
794 fn lower_expr_async_closure(
796 capture_clause: CaptureBy,
801 ) -> hir::ExprKind<'hir> {
803 FnDecl { inputs: decl.inputs.clone(), output: FnRetTy::Default(fn_decl_span) };
804 // We need to lower the declaration outside the new scope, because we
805 // have to conserve the state of being inside a loop condition for the
806 // closure argument types.
807 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
809 self.with_new_scopes(move |this| {
810 // FIXME(cramertj): allow `async` non-`move` closures with arguments.
811 if capture_clause == CaptureBy::Ref && !decl.inputs.is_empty() {
816 "`async` non-`move` closures with parameters are not currently supported",
819 "consider using `let` statements to manually capture \
820 variables by reference before entering an `async move` closure",
825 // Transform `async |x: u8| -> X { ... }` into
826 // `|x: u8| future_from_generator(|| -> X { ... })`.
827 let body_id = this.lower_fn_body(&outer_decl, |this| {
829 if let FnRetTy::Ty(ty) = &decl.output { Some(ty.clone()) } else { None };
830 let async_body = this.make_async_expr(
835 hir::AsyncGeneratorKind::Closure,
836 |this| this.with_new_scopes(|this| this.lower_expr_mut(body)),
838 this.expr(fn_decl_span, async_body, ThinVec::new())
840 hir::ExprKind::Closure(capture_clause, fn_decl, body_id, fn_decl_span, None)
844 /// Destructure the LHS of complex assignments.
845 /// For instance, lower `(a, b) = t` to `{ let (lhs1, lhs2) = t; a = lhs1; b = lhs2; }`.
846 fn lower_expr_assign(
852 ) -> hir::ExprKind<'hir> {
853 // Return early in case of an ordinary assignment.
854 fn is_ordinary(lhs: &Expr) -> bool {
856 ExprKind::Tup(..) => false,
857 ExprKind::Paren(e) => {
859 // We special-case `(..)` for consistency with patterns.
860 ExprKind::Range(None, None, RangeLimits::HalfOpen) => false,
867 if is_ordinary(lhs) {
868 return hir::ExprKind::Assign(self.lower_expr(lhs), self.lower_expr(rhs), eq_sign_span);
870 if !self.sess.features_untracked().destructuring_assignment {
872 &self.sess.parse_sess,
873 sym::destructuring_assignment,
875 "destructuring assignments are unstable",
877 .span_label(lhs.span, "cannot assign to this expression")
881 let mut assignments = vec![];
883 // The LHS becomes a pattern: `(lhs1, lhs2)`.
884 let pat = self.destructure_assign(lhs, eq_sign_span, &mut assignments);
885 let rhs = self.lower_expr(rhs);
887 // Introduce a `let` for destructuring: `let (lhs1, lhs2) = t`.
888 let destructure_let = self.stmt_let_pat(
893 hir::LocalSource::AssignDesugar(eq_sign_span),
896 // `a = lhs1; b = lhs2;`.
899 .alloc_from_iter(std::iter::once(destructure_let).chain(assignments.into_iter()));
901 // Wrap everything in a block.
902 hir::ExprKind::Block(&self.block_all(whole_span, stmts, None), None)
905 /// Convert the LHS of a destructuring assignment to a pattern.
906 /// Each sub-assignment is recorded in `assignments`.
907 fn destructure_assign(
911 assignments: &mut Vec<hir::Stmt<'hir>>,
912 ) -> &'hir hir::Pat<'hir> {
915 ExprKind::Tup(elements) => {
917 self.destructure_sequence(elements, "tuple", eq_sign_span, assignments);
918 let tuple_pat = hir::PatKind::Tuple(pats, rest.map(|r| r.0));
919 return self.pat_without_dbm(lhs.span, tuple_pat);
921 ExprKind::Paren(e) => {
922 // We special-case `(..)` for consistency with patterns.
923 if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
924 let tuple_pat = hir::PatKind::Tuple(&[], Some(0));
925 return self.pat_without_dbm(lhs.span, tuple_pat);
927 return self.destructure_assign(e, eq_sign_span, assignments);
932 // Treat all other cases as normal lvalue.
933 let ident = Ident::new(sym::lhs, lhs.span);
934 let (pat, binding) = self.pat_ident(lhs.span, ident);
935 let ident = self.expr_ident(lhs.span, ident, binding);
936 let assign = hir::ExprKind::Assign(self.lower_expr(lhs), ident, eq_sign_span);
937 let expr = self.expr(lhs.span, assign, ThinVec::new());
938 assignments.push(self.stmt_expr(lhs.span, expr));
942 /// Destructure a sequence of expressions occurring on the LHS of an assignment.
943 /// Such a sequence occurs in a tuple (struct)/slice.
944 /// Return a sequence of corresponding patterns, and the index and the span of `..` if it
946 /// Each sub-assignment is recorded in `assignments`.
947 fn destructure_sequence(
949 elements: &[AstP<Expr>],
952 assignments: &mut Vec<hir::Stmt<'hir>>,
953 ) -> (&'hir [&'hir hir::Pat<'hir>], Option<(usize, Span)>) {
956 self.arena.alloc_from_iter(elements.iter().enumerate().filter_map(|(i, e)| {
957 // Check for `..` pattern.
958 if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
959 if let Some((_, prev_span)) = rest {
960 self.ban_extra_rest_pat(e.span, prev_span, ctx);
962 rest = Some((i, e.span));
966 Some(self.destructure_assign(e, eq_sign_span, assignments))
972 /// Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`.
973 fn lower_expr_range_closed(&mut self, span: Span, e1: &Expr, e2: &Expr) -> hir::ExprKind<'hir> {
974 let e1 = self.lower_expr_mut(e1);
975 let e2 = self.lower_expr_mut(e2);
976 let fn_path = hir::QPath::LangItem(hir::LangItem::RangeInclusiveNew, span);
978 self.arena.alloc(self.expr(span, hir::ExprKind::Path(fn_path), ThinVec::new()));
979 hir::ExprKind::Call(fn_expr, arena_vec![self; e1, e2])
988 ) -> hir::ExprKind<'hir> {
989 use rustc_ast::RangeLimits::*;
991 let lang_item = match (e1, e2, lims) {
992 (None, None, HalfOpen) => hir::LangItem::RangeFull,
993 (Some(..), None, HalfOpen) => hir::LangItem::RangeFrom,
994 (None, Some(..), HalfOpen) => hir::LangItem::RangeTo,
995 (Some(..), Some(..), HalfOpen) => hir::LangItem::Range,
996 (None, Some(..), Closed) => hir::LangItem::RangeToInclusive,
997 (Some(..), Some(..), Closed) => unreachable!(),
998 (_, None, Closed) => {
999 self.diagnostic().span_fatal(span, "inclusive range with no end").raise()
1003 let fields = self.arena.alloc_from_iter(
1004 e1.iter().map(|e| ("start", e)).chain(e2.iter().map(|e| ("end", e))).map(|(s, e)| {
1005 let expr = self.lower_expr(&e);
1006 let ident = Ident::new(Symbol::intern(s), e.span);
1007 self.field(ident, expr, e.span)
1011 hir::ExprKind::Struct(self.arena.alloc(hir::QPath::LangItem(lang_item, span)), fields, None)
1014 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
1015 let target_id = match destination {
1017 if let Some(loop_id) = self.resolver.get_label_res(id) {
1018 Ok(self.lower_node_id(loop_id))
1020 Err(hir::LoopIdError::UnresolvedLabel)
1027 .map(|id| Ok(self.lower_node_id(id)))
1028 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope)),
1030 hir::Destination { label: destination.map(|(_, label)| label), target_id }
1033 fn lower_jump_destination(&mut self, id: NodeId, opt_label: Option<Label>) -> hir::Destination {
1034 if self.is_in_loop_condition && opt_label.is_none() {
1037 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition),
1040 self.lower_loop_destination(opt_label.map(|label| (id, label)))
1044 fn with_catch_scope<T>(&mut self, catch_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1045 let len = self.catch_scopes.len();
1046 self.catch_scopes.push(catch_id);
1048 let result = f(self);
1051 self.catch_scopes.len(),
1052 "catch scopes should be added and removed in stack order"
1055 self.catch_scopes.pop().unwrap();
1060 fn with_loop_scope<T>(&mut self, loop_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1061 // We're no longer in the base loop's condition; we're in another loop.
1062 let was_in_loop_condition = self.is_in_loop_condition;
1063 self.is_in_loop_condition = false;
1065 let len = self.loop_scopes.len();
1066 self.loop_scopes.push(loop_id);
1068 let result = f(self);
1071 self.loop_scopes.len(),
1072 "loop scopes should be added and removed in stack order"
1075 self.loop_scopes.pop().unwrap();
1077 self.is_in_loop_condition = was_in_loop_condition;
1082 fn with_loop_condition_scope<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
1083 let was_in_loop_condition = self.is_in_loop_condition;
1084 self.is_in_loop_condition = true;
1086 let result = f(self);
1088 self.is_in_loop_condition = was_in_loop_condition;
1093 fn lower_expr_asm(&mut self, sp: Span, asm: &InlineAsm) -> hir::ExprKind<'hir> {
1094 if self.sess.asm_arch.is_none() {
1095 struct_span_err!(self.sess, sp, E0472, "asm! is unsupported on this target").emit();
1097 if asm.options.contains(InlineAsmOptions::ATT_SYNTAX)
1100 Some(asm::InlineAsmArch::X86 | asm::InlineAsmArch::X86_64)
1104 .struct_span_err(sp, "the `att_syntax` option is only supported on x86")
1108 // Lower operands to HIR, filter_map skips any operands with invalid
1109 // register classes.
1110 let sess = self.sess;
1111 let operands: Vec<_> = asm
1114 .filter_map(|(op, op_sp)| {
1115 let lower_reg = |reg| {
1117 InlineAsmRegOrRegClass::Reg(s) => asm::InlineAsmRegOrRegClass::Reg(
1118 asm::InlineAsmReg::parse(
1120 |feature| sess.target_features.contains(&Symbol::intern(feature)),
1125 let msg = format!("invalid register `{}`: {}", s.as_str(), e);
1126 sess.struct_span_err(*op_sp, &msg).emit();
1130 InlineAsmRegOrRegClass::RegClass(s) => {
1131 asm::InlineAsmRegOrRegClass::RegClass(
1132 asm::InlineAsmRegClass::parse(sess.asm_arch?, s)
1135 "invalid register class `{}`: {}",
1139 sess.struct_span_err(*op_sp, &msg).emit();
1147 // lower_reg is executed last because we need to lower all
1148 // sub-expressions even if we throw them away later.
1149 let op = match *op {
1150 InlineAsmOperand::In { reg, ref expr } => hir::InlineAsmOperand::In {
1151 expr: self.lower_expr_mut(expr),
1152 reg: lower_reg(reg)?,
1154 InlineAsmOperand::Out { reg, late, ref expr } => hir::InlineAsmOperand::Out {
1156 expr: expr.as_ref().map(|expr| self.lower_expr_mut(expr)),
1157 reg: lower_reg(reg)?,
1159 InlineAsmOperand::InOut { reg, late, ref expr } => {
1160 hir::InlineAsmOperand::InOut {
1162 expr: self.lower_expr_mut(expr),
1163 reg: lower_reg(reg)?,
1166 InlineAsmOperand::SplitInOut { reg, late, ref in_expr, ref out_expr } => {
1167 hir::InlineAsmOperand::SplitInOut {
1169 in_expr: self.lower_expr_mut(in_expr),
1170 out_expr: out_expr.as_ref().map(|expr| self.lower_expr_mut(expr)),
1171 reg: lower_reg(reg)?,
1174 InlineAsmOperand::Const { ref expr } => {
1175 hir::InlineAsmOperand::Const { expr: self.lower_expr_mut(expr) }
1177 InlineAsmOperand::Sym { ref expr } => {
1178 hir::InlineAsmOperand::Sym { expr: self.lower_expr_mut(expr) }
1185 // Stop if there were any errors when lowering the register classes
1186 if operands.len() != asm.operands.len() || sess.asm_arch.is_none() {
1187 return hir::ExprKind::Err;
1190 // Validate template modifiers against the register classes for the operands
1191 let asm_arch = sess.asm_arch.unwrap();
1192 for p in &asm.template {
1193 if let InlineAsmTemplatePiece::Placeholder {
1195 modifier: Some(modifier),
1196 span: placeholder_span,
1199 let op_sp = asm.operands[operand_idx].1;
1200 match &operands[operand_idx] {
1201 hir::InlineAsmOperand::In { reg, .. }
1202 | hir::InlineAsmOperand::Out { reg, .. }
1203 | hir::InlineAsmOperand::InOut { reg, .. }
1204 | hir::InlineAsmOperand::SplitInOut { reg, .. } => {
1205 let class = reg.reg_class();
1206 let valid_modifiers = class.valid_modifiers(asm_arch);
1207 if !valid_modifiers.contains(&modifier) {
1208 let mut err = sess.struct_span_err(
1210 "invalid asm template modifier for this register class",
1212 err.span_label(placeholder_span, "template modifier");
1213 err.span_label(op_sp, "argument");
1214 if !valid_modifiers.is_empty() {
1215 let mut mods = format!("`{}`", valid_modifiers[0]);
1216 for m in &valid_modifiers[1..] {
1217 let _ = write!(mods, ", `{}`", m);
1220 "the `{}` register class supports \
1221 the following template modifiers: {}",
1227 "the `{}` register class does not support template modifiers",
1234 hir::InlineAsmOperand::Const { .. } => {
1235 let mut err = sess.struct_span_err(
1237 "asm template modifiers are not allowed for `const` arguments",
1239 err.span_label(placeholder_span, "template modifier");
1240 err.span_label(op_sp, "argument");
1243 hir::InlineAsmOperand::Sym { .. } => {
1244 let mut err = sess.struct_span_err(
1246 "asm template modifiers are not allowed for `sym` arguments",
1248 err.span_label(placeholder_span, "template modifier");
1249 err.span_label(op_sp, "argument");
1256 let mut used_input_regs = FxHashMap::default();
1257 let mut used_output_regs = FxHashMap::default();
1258 for (idx, op) in operands.iter().enumerate() {
1259 let op_sp = asm.operands[idx].1;
1260 if let Some(reg) = op.reg() {
1261 // Validate register classes against currently enabled target
1262 // features. We check that at least one type is available for
1263 // the current target.
1264 let reg_class = reg.reg_class();
1265 let mut required_features: Vec<&str> = vec![];
1266 for &(_, feature) in reg_class.supported_types(asm_arch) {
1267 if let Some(feature) = feature {
1268 if self.sess.target_features.contains(&Symbol::intern(feature)) {
1269 required_features.clear();
1272 required_features.push(feature);
1275 required_features.clear();
1279 // We are sorting primitive strs here and can use unstable sort here
1280 required_features.sort_unstable();
1281 required_features.dedup();
1282 match &required_features[..] {
1286 "register class `{}` requires the `{}` target feature",
1290 sess.struct_span_err(op_sp, &msg).emit();
1294 "register class `{}` requires at least one target feature: {}",
1298 sess.struct_span_err(op_sp, &msg).emit();
1302 // Check for conflicts between explicit register operands.
1303 if let asm::InlineAsmRegOrRegClass::Reg(reg) = reg {
1304 let (input, output) = match op {
1305 hir::InlineAsmOperand::In { .. } => (true, false),
1306 // Late output do not conflict with inputs, but normal outputs do
1307 hir::InlineAsmOperand::Out { late, .. } => (!late, true),
1308 hir::InlineAsmOperand::InOut { .. }
1309 | hir::InlineAsmOperand::SplitInOut { .. } => (true, true),
1310 hir::InlineAsmOperand::Const { .. } | hir::InlineAsmOperand::Sym { .. } => {
1315 // Flag to output the error only once per operand
1316 let mut skip = false;
1317 reg.overlapping_regs(|r| {
1318 let mut check = |used_regs: &mut FxHashMap<asm::InlineAsmReg, usize>,
1320 match used_regs.entry(r) {
1321 Entry::Occupied(o) => {
1327 let idx2 = *o.get();
1328 let op2 = &operands[idx2];
1329 let op_sp2 = asm.operands[idx2].1;
1330 let reg2 = match op2.reg() {
1331 Some(asm::InlineAsmRegOrRegClass::Reg(r)) => r,
1332 _ => unreachable!(),
1336 "register `{}` conflicts with register `{}`",
1340 let mut err = sess.struct_span_err(op_sp, &msg);
1341 err.span_label(op_sp, &format!("register `{}`", reg.name()));
1342 err.span_label(op_sp2, &format!("register `{}`", reg2.name()));
1346 hir::InlineAsmOperand::In { .. },
1347 hir::InlineAsmOperand::Out { late, .. },
1350 hir::InlineAsmOperand::Out { late, .. },
1351 hir::InlineAsmOperand::In { .. },
1354 let out_op_sp = if input { op_sp2 } else { op_sp };
1355 let msg = "use `lateout` instead of \
1356 `out` to avoid conflict";
1357 err.span_help(out_op_sp, msg);
1364 Entry::Vacant(v) => {
1370 check(&mut used_input_regs, true);
1373 check(&mut used_output_regs, false);
1380 let operands = self.arena.alloc_from_iter(operands);
1381 let template = self.arena.alloc_from_iter(asm.template.iter().cloned());
1382 let line_spans = self.arena.alloc_slice(&asm.line_spans[..]);
1383 let hir_asm = hir::InlineAsm { template, operands, options: asm.options, line_spans };
1384 hir::ExprKind::InlineAsm(self.arena.alloc(hir_asm))
1387 fn lower_expr_llvm_asm(&mut self, asm: &LlvmInlineAsm) -> hir::ExprKind<'hir> {
1388 let inner = hir::LlvmInlineAsmInner {
1389 inputs: asm.inputs.iter().map(|&(c, _)| c).collect(),
1393 .map(|out| hir::LlvmInlineAsmOutput {
1394 constraint: out.constraint,
1396 is_indirect: out.is_indirect,
1397 span: out.expr.span,
1401 asm_str_style: asm.asm_str_style,
1402 clobbers: asm.clobbers.clone(),
1403 volatile: asm.volatile,
1404 alignstack: asm.alignstack,
1405 dialect: asm.dialect,
1407 let hir_asm = hir::LlvmInlineAsm {
1409 inputs_exprs: self.arena.alloc_from_iter(
1410 asm.inputs.iter().map(|&(_, ref input)| self.lower_expr_mut(input)),
1414 .alloc_from_iter(asm.outputs.iter().map(|out| self.lower_expr_mut(&out.expr))),
1416 hir::ExprKind::LlvmInlineAsm(self.arena.alloc(hir_asm))
1419 fn lower_field(&mut self, f: &Field) -> hir::Field<'hir> {
1421 hir_id: self.next_id(),
1423 expr: self.lower_expr(&f.expr),
1425 is_shorthand: f.is_shorthand,
1429 fn lower_expr_yield(&mut self, span: Span, opt_expr: Option<&Expr>) -> hir::ExprKind<'hir> {
1430 match self.generator_kind {
1431 Some(hir::GeneratorKind::Gen) => {}
1432 Some(hir::GeneratorKind::Async(_)) => {
1437 "`async` generators are not yet supported"
1441 None => self.generator_kind = Some(hir::GeneratorKind::Gen),
1445 opt_expr.as_ref().map(|x| self.lower_expr(x)).unwrap_or_else(|| self.expr_unit(span));
1447 hir::ExprKind::Yield(expr, hir::YieldSource::Yield)
1450 /// Desugar `ExprForLoop` from: `[opt_ident]: for <pat> in <head> <body>` into:
1453 /// let result = match ::std::iter::IntoIterator::into_iter(<head>) {
1455 /// [opt_ident]: loop {
1457 /// match ::std::iter::Iterator::next(&mut iter) {
1458 /// ::std::option::Option::Some(val) => __next = val,
1459 /// ::std::option::Option::None => break
1461 /// let <pat> = __next;
1462 /// StmtKind::Expr(<body>);
1475 opt_label: Option<Label>,
1476 ) -> hir::Expr<'hir> {
1477 let orig_head_span = head.span;
1479 let mut head = self.lower_expr_mut(head);
1480 let desugared_span = self.mark_span_with_reason(
1481 DesugaringKind::ForLoop(ForLoopLoc::Head),
1485 head.span = desugared_span;
1487 let iter = Ident::with_dummy_span(sym::iter);
1489 let next_ident = Ident::with_dummy_span(sym::__next);
1490 let (next_pat, next_pat_hid) = self.pat_ident_binding_mode(
1493 hir::BindingAnnotation::Mutable,
1496 // `::std::option::Option::Some(val) => __next = val`
1498 let val_ident = Ident::with_dummy_span(sym::val);
1499 let (val_pat, val_pat_hid) = self.pat_ident(pat.span, val_ident);
1500 let val_expr = self.expr_ident(pat.span, val_ident, val_pat_hid);
1501 let next_expr = self.expr_ident(pat.span, next_ident, next_pat_hid);
1502 let assign = self.arena.alloc(self.expr(
1504 hir::ExprKind::Assign(next_expr, val_expr, pat.span),
1507 let some_pat = self.pat_some(pat.span, val_pat);
1508 self.arm(some_pat, assign)
1511 // `::std::option::Option::None => break`
1514 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
1515 let pat = self.pat_none(e.span);
1516 self.arm(pat, break_expr)
1520 let (iter_pat, iter_pat_nid) =
1521 self.pat_ident_binding_mode(desugared_span, iter, hir::BindingAnnotation::Mutable);
1523 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
1525 let iter = self.expr_ident(desugared_span, iter, iter_pat_nid);
1526 let ref_mut_iter = self.expr_mut_addr_of(desugared_span, iter);
1527 let next_expr = self.expr_call_lang_item_fn(
1529 hir::LangItem::IteratorNext,
1530 arena_vec![self; ref_mut_iter],
1532 let arms = arena_vec![self; pat_arm, break_arm];
1534 self.expr_match(desugared_span, next_expr, arms, hir::MatchSource::ForLoopDesugar)
1536 let match_stmt = self.stmt_expr(desugared_span, match_expr);
1538 let next_expr = self.expr_ident(desugared_span, next_ident, next_pat_hid);
1541 let next_let = self.stmt_let_pat(
1546 hir::LocalSource::ForLoopDesugar,
1549 // `let <pat> = __next`
1550 let pat = self.lower_pat(pat);
1551 let pat_let = self.stmt_let_pat(
1556 hir::LocalSource::ForLoopDesugar,
1559 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
1560 let body_expr = self.expr_block(body_block, ThinVec::new());
1561 let body_stmt = self.stmt_expr(body.span, body_expr);
1563 let loop_block = self.block_all(
1565 arena_vec![self; next_let, match_stmt, pat_let, body_stmt],
1569 // `[opt_ident]: loop { ... }`
1570 let kind = hir::ExprKind::Loop(loop_block, opt_label, hir::LoopSource::ForLoop);
1571 let loop_expr = self.arena.alloc(hir::Expr {
1572 hir_id: self.lower_node_id(e.id),
1575 attrs: ThinVec::new(),
1578 // `mut iter => { ... }`
1579 let iter_arm = self.arm(iter_pat, loop_expr);
1581 let into_iter_span = self.mark_span_with_reason(
1582 DesugaringKind::ForLoop(ForLoopLoc::IntoIter),
1587 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
1588 let into_iter_expr = {
1589 self.expr_call_lang_item_fn(
1591 hir::LangItem::IntoIterIntoIter,
1592 arena_vec![self; head],
1596 let match_expr = self.arena.alloc(self.expr_match(
1599 arena_vec![self; iter_arm],
1600 hir::MatchSource::ForLoopDesugar,
1603 let attrs: Vec<_> = e.attrs.iter().map(|a| self.lower_attr(a)).collect();
1605 // This is effectively `{ let _result = ...; _result }`.
1606 // The construct was introduced in #21984 and is necessary to make sure that
1607 // temporaries in the `head` expression are dropped and do not leak to the
1608 // surrounding scope of the `match` since the `match` is not a terminating scope.
1610 // Also, add the attributes to the outer returned expr node.
1611 self.expr_drop_temps_mut(desugared_span, match_expr, attrs.into())
1614 /// Desugar `ExprKind::Try` from: `<expr>?` into:
1616 /// match Try::into_result(<expr>) {
1617 /// Ok(val) => #[allow(unreachable_code)] val,
1618 /// Err(err) => #[allow(unreachable_code)]
1619 /// // If there is an enclosing `try {...}`:
1620 /// break 'catch_target Try::from_error(From::from(err)),
1622 /// return Try::from_error(From::from(err)),
1625 fn lower_expr_try(&mut self, span: Span, sub_expr: &Expr) -> hir::ExprKind<'hir> {
1626 let unstable_span = self.mark_span_with_reason(
1627 DesugaringKind::QuestionMark,
1629 self.allow_try_trait.clone(),
1631 let try_span = self.sess.source_map().end_point(span);
1632 let try_span = self.mark_span_with_reason(
1633 DesugaringKind::QuestionMark,
1635 self.allow_try_trait.clone(),
1638 // `Try::into_result(<expr>)`
1641 let sub_expr = self.lower_expr_mut(sub_expr);
1643 self.expr_call_lang_item_fn(
1645 hir::LangItem::TryIntoResult,
1646 arena_vec![self; sub_expr],
1650 // `#[allow(unreachable_code)]`
1652 // `allow(unreachable_code)`
1654 let allow_ident = Ident::new(sym::allow, span);
1655 let uc_ident = Ident::new(sym::unreachable_code, span);
1656 let uc_nested = attr::mk_nested_word_item(uc_ident);
1657 attr::mk_list_item(allow_ident, vec![uc_nested])
1659 attr::mk_attr_outer(allow)
1661 let attrs = vec![attr];
1663 // `Ok(val) => #[allow(unreachable_code)] val,`
1665 let val_ident = Ident::with_dummy_span(sym::val);
1666 let (val_pat, val_pat_nid) = self.pat_ident(span, val_ident);
1667 let val_expr = self.arena.alloc(self.expr_ident_with_attrs(
1671 ThinVec::from(attrs.clone()),
1673 let ok_pat = self.pat_ok(span, val_pat);
1674 self.arm(ok_pat, val_expr)
1677 // `Err(err) => #[allow(unreachable_code)]
1678 // return Try::from_error(From::from(err)),`
1680 let err_ident = Ident::with_dummy_span(sym::err);
1681 let (err_local, err_local_nid) = self.pat_ident(try_span, err_ident);
1683 let err_expr = self.expr_ident_mut(try_span, err_ident, err_local_nid);
1684 self.expr_call_lang_item_fn(
1686 hir::LangItem::FromFrom,
1687 arena_vec![self; err_expr],
1690 let from_err_expr = self.wrap_in_try_constructor(
1691 hir::LangItem::TryFromError,
1696 let thin_attrs = ThinVec::from(attrs);
1697 let catch_scope = self.catch_scopes.last().copied();
1698 let ret_expr = if let Some(catch_node) = catch_scope {
1699 let target_id = Ok(self.lower_node_id(catch_node));
1700 self.arena.alloc(self.expr(
1702 hir::ExprKind::Break(
1703 hir::Destination { label: None, target_id },
1704 Some(from_err_expr),
1709 self.arena.alloc(self.expr(
1711 hir::ExprKind::Ret(Some(from_err_expr)),
1716 let err_pat = self.pat_err(try_span, err_local);
1717 self.arm(err_pat, ret_expr)
1720 hir::ExprKind::Match(
1722 arena_vec![self; err_arm, ok_arm],
1723 hir::MatchSource::TryDesugar,
1727 // =========================================================================
1728 // Helper methods for building HIR.
1729 // =========================================================================
1731 /// Constructs a `true` or `false` literal expression.
1732 pub(super) fn expr_bool(&mut self, span: Span, val: bool) -> &'hir hir::Expr<'hir> {
1733 let lit = Spanned { span, node: LitKind::Bool(val) };
1734 self.arena.alloc(self.expr(span, hir::ExprKind::Lit(lit), ThinVec::new()))
1737 /// Wrap the given `expr` in a terminating scope using `hir::ExprKind::DropTemps`.
1739 /// In terms of drop order, it has the same effect as wrapping `expr` in
1740 /// `{ let _t = $expr; _t }` but should provide better compile-time performance.
1742 /// The drop order can be important in e.g. `if expr { .. }`.
1743 pub(super) fn expr_drop_temps(
1746 expr: &'hir hir::Expr<'hir>,
1748 ) -> &'hir hir::Expr<'hir> {
1749 self.arena.alloc(self.expr_drop_temps_mut(span, expr, attrs))
1752 pub(super) fn expr_drop_temps_mut(
1755 expr: &'hir hir::Expr<'hir>,
1757 ) -> hir::Expr<'hir> {
1758 self.expr(span, hir::ExprKind::DropTemps(expr), attrs)
1764 arg: &'hir hir::Expr<'hir>,
1765 arms: &'hir [hir::Arm<'hir>],
1766 source: hir::MatchSource,
1767 ) -> hir::Expr<'hir> {
1768 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
1771 fn expr_break(&mut self, span: Span, attrs: AttrVec) -> &'hir hir::Expr<'hir> {
1772 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
1773 self.arena.alloc(self.expr(span, expr_break, attrs))
1776 fn expr_mut_addr_of(&mut self, span: Span, e: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
1779 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Mut, e),
1784 fn expr_unit(&mut self, sp: Span) -> &'hir hir::Expr<'hir> {
1785 self.arena.alloc(self.expr(sp, hir::ExprKind::Tup(&[]), ThinVec::new()))
1791 e: &'hir hir::Expr<'hir>,
1792 args: &'hir [hir::Expr<'hir>],
1793 ) -> hir::Expr<'hir> {
1794 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
1800 e: &'hir hir::Expr<'hir>,
1801 args: &'hir [hir::Expr<'hir>],
1802 ) -> &'hir hir::Expr<'hir> {
1803 self.arena.alloc(self.expr_call_mut(span, e, args))
1806 fn expr_call_lang_item_fn_mut(
1809 lang_item: hir::LangItem,
1810 args: &'hir [hir::Expr<'hir>],
1811 ) -> hir::Expr<'hir> {
1812 let path = self.arena.alloc(self.expr_lang_item_path(span, lang_item, ThinVec::new()));
1813 self.expr_call_mut(span, path, args)
1816 fn expr_call_lang_item_fn(
1819 lang_item: hir::LangItem,
1820 args: &'hir [hir::Expr<'hir>],
1821 ) -> &'hir hir::Expr<'hir> {
1822 self.arena.alloc(self.expr_call_lang_item_fn_mut(span, lang_item, args))
1825 fn expr_lang_item_path(
1828 lang_item: hir::LangItem,
1830 ) -> hir::Expr<'hir> {
1831 self.expr(span, hir::ExprKind::Path(hir::QPath::LangItem(lang_item, span)), attrs)
1834 pub(super) fn expr_ident(
1838 binding: hir::HirId,
1839 ) -> &'hir hir::Expr<'hir> {
1840 self.arena.alloc(self.expr_ident_mut(sp, ident, binding))
1843 pub(super) fn expr_ident_mut(
1847 binding: hir::HirId,
1848 ) -> hir::Expr<'hir> {
1849 self.expr_ident_with_attrs(sp, ident, binding, ThinVec::new())
1852 fn expr_ident_with_attrs(
1856 binding: hir::HirId,
1858 ) -> hir::Expr<'hir> {
1859 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
1861 self.arena.alloc(hir::Path {
1863 res: Res::Local(binding),
1864 segments: arena_vec![self; hir::PathSegment::from_ident(ident)],
1868 self.expr(span, expr_path, attrs)
1871 fn expr_unsafe(&mut self, expr: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
1872 let hir_id = self.next_id();
1873 let span = expr.span;
1876 hir::ExprKind::Block(
1877 self.arena.alloc(hir::Block {
1881 rules: hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::CompilerGenerated),
1883 targeted_by_break: false,
1891 fn expr_block_empty(&mut self, span: Span) -> &'hir hir::Expr<'hir> {
1892 let blk = self.block_all(span, &[], None);
1893 let expr = self.expr_block(blk, ThinVec::new());
1894 self.arena.alloc(expr)
1897 pub(super) fn expr_block(
1899 b: &'hir hir::Block<'hir>,
1901 ) -> hir::Expr<'hir> {
1902 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
1908 kind: hir::ExprKind<'hir>,
1910 ) -> hir::Expr<'hir> {
1911 hir::Expr { hir_id: self.next_id(), kind, span, attrs }
1914 fn field(&mut self, ident: Ident, expr: &'hir hir::Expr<'hir>, span: Span) -> hir::Field<'hir> {
1915 hir::Field { hir_id: self.next_id(), ident, span, expr, is_shorthand: false }
1918 fn arm(&mut self, pat: &'hir hir::Pat<'hir>, expr: &'hir hir::Expr<'hir>) -> hir::Arm<'hir> {
1920 hir_id: self.next_id(),