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 rest) => {
191 let rest = match rest {
192 StructRest::Base(e) => Some(self.lower_expr(e)),
193 StructRest::Rest(sp) => {
195 .struct_span_err(*sp, "base expression required after `..`")
196 .span_label(*sp, "add a base expression here")
198 Some(&*self.arena.alloc(self.expr_err(*sp)))
200 StructRest::None => None,
202 hir::ExprKind::Struct(
203 self.arena.alloc(self.lower_qpath(
208 ImplTraitContext::disallowed(),
210 self.arena.alloc_from_iter(fields.iter().map(|x| self.lower_field(x))),
214 ExprKind::Yield(ref opt_expr) => self.lower_expr_yield(e.span, opt_expr.as_deref()),
215 ExprKind::Err => hir::ExprKind::Err,
216 ExprKind::Try(ref sub_expr) => self.lower_expr_try(e.span, sub_expr),
217 ExprKind::Paren(ref ex) => {
218 let mut ex = self.lower_expr_mut(ex);
219 // Include parens in span, but only if it is a super-span.
220 if e.span.contains(ex.span) {
223 // Merge attributes into the inner expression.
224 let mut attrs: Vec<_> = e.attrs.iter().map(|a| self.lower_attr(a)).collect();
225 attrs.extend::<Vec<_>>(ex.attrs.into());
226 ex.attrs = attrs.into();
230 // Desugar `ExprForLoop`
231 // from: `[opt_ident]: for <pat> in <head> <body>`
232 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
233 return self.lower_expr_for(e, pat, head, body, opt_label);
235 ExprKind::MacCall(_) => panic!("{:?} shouldn't exist here", e.span),
239 hir_id: self.lower_node_id(e.id),
242 attrs: e.attrs.iter().map(|a| self.lower_attr(a)).collect::<Vec<_>>().into(),
247 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
249 UnOp::Deref => hir::UnOp::UnDeref,
250 UnOp::Not => hir::UnOp::UnNot,
251 UnOp::Neg => hir::UnOp::UnNeg,
255 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
258 BinOpKind::Add => hir::BinOpKind::Add,
259 BinOpKind::Sub => hir::BinOpKind::Sub,
260 BinOpKind::Mul => hir::BinOpKind::Mul,
261 BinOpKind::Div => hir::BinOpKind::Div,
262 BinOpKind::Rem => hir::BinOpKind::Rem,
263 BinOpKind::And => hir::BinOpKind::And,
264 BinOpKind::Or => hir::BinOpKind::Or,
265 BinOpKind::BitXor => hir::BinOpKind::BitXor,
266 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
267 BinOpKind::BitOr => hir::BinOpKind::BitOr,
268 BinOpKind::Shl => hir::BinOpKind::Shl,
269 BinOpKind::Shr => hir::BinOpKind::Shr,
270 BinOpKind::Eq => hir::BinOpKind::Eq,
271 BinOpKind::Lt => hir::BinOpKind::Lt,
272 BinOpKind::Le => hir::BinOpKind::Le,
273 BinOpKind::Ne => hir::BinOpKind::Ne,
274 BinOpKind::Ge => hir::BinOpKind::Ge,
275 BinOpKind::Gt => hir::BinOpKind::Gt,
281 /// Emit an error and lower `ast::ExprKind::Let(pat, scrutinee)` into:
283 /// match scrutinee { pats => true, _ => false }
285 fn lower_expr_let(&mut self, span: Span, pat: &Pat, scrutinee: &Expr) -> hir::ExprKind<'hir> {
286 // If we got here, the `let` expression is not allowed.
288 if self.sess.opts.unstable_features.is_nightly_build() {
290 .struct_span_err(span, "`let` expressions are not supported here")
291 .note("only supported directly in conditions of `if`- and `while`-expressions")
292 .note("as well as when nested within `&&` and parenthesis in those conditions")
296 .struct_span_err(span, "expected expression, found statement (`let`)")
297 .note("variable declaration using `let` is a statement")
301 // For better recovery, we emit:
303 // match scrutinee { pat => true, _ => false }
305 // While this doesn't fully match the user's intent, it has key advantages:
306 // 1. We can avoid using `abort_if_errors`.
307 // 2. We can typeck both `pat` and `scrutinee`.
308 // 3. `pat` is allowed to be refutable.
309 // 4. The return type of the block is `bool` which seems like what the user wanted.
310 let scrutinee = self.lower_expr(scrutinee);
312 let pat = self.lower_pat(pat);
313 let expr = self.expr_bool(span, true);
317 let pat = self.pat_wild(span);
318 let expr = self.expr_bool(span, false);
321 hir::ExprKind::Match(
323 arena_vec![self; then_arm, else_arm],
324 hir::MatchSource::Normal,
333 else_opt: Option<&Expr>,
334 ) -> hir::ExprKind<'hir> {
335 // FIXME(#53667): handle lowering of && and parens.
337 // `_ => else_block` where `else_block` is `{}` if there's `None`:
338 let else_pat = self.pat_wild(span);
339 let (else_expr, contains_else_clause) = match else_opt {
340 None => (self.expr_block_empty(span), false),
341 Some(els) => (self.lower_expr(els), true),
343 let else_arm = self.arm(else_pat, else_expr);
345 // Handle then + scrutinee:
346 let then_expr = self.lower_block_expr(then);
347 let (then_pat, scrutinee, desugar) = match cond.kind {
348 // `<pat> => <then>`:
349 ExprKind::Let(ref pat, ref scrutinee) => {
350 let scrutinee = self.lower_expr(scrutinee);
351 let pat = self.lower_pat(pat);
352 (pat, scrutinee, hir::MatchSource::IfLetDesugar { contains_else_clause })
357 let cond = self.lower_expr(cond);
359 self.mark_span_with_reason(DesugaringKind::CondTemporary, cond.span, None);
360 // Wrap in a construct equivalent to `{ let _t = $cond; _t }`
361 // to preserve drop semantics since `if cond { ... }` does not
362 // let temporaries live outside of `cond`.
363 let cond = self.expr_drop_temps(span_block, cond, ThinVec::new());
364 let pat = self.pat_bool(span, true);
365 (pat, cond, hir::MatchSource::IfDesugar { contains_else_clause })
368 let then_arm = self.arm(then_pat, self.arena.alloc(then_expr));
370 hir::ExprKind::Match(scrutinee, arena_vec![self; then_arm, else_arm], desugar)
373 fn lower_expr_while_in_loop_scope(
378 opt_label: Option<Label>,
379 ) -> hir::ExprKind<'hir> {
380 // FIXME(#53667): handle lowering of && and parens.
382 // Note that the block AND the condition are evaluated in the loop scope.
383 // This is done to allow `break` from inside the condition of the loop.
387 let else_pat = self.pat_wild(span);
388 let else_expr = self.expr_break(span, ThinVec::new());
389 self.arm(else_pat, else_expr)
392 // Handle then + scrutinee:
393 let then_expr = self.lower_block_expr(body);
394 let (then_pat, scrutinee, desugar, source) = match cond.kind {
395 ExprKind::Let(ref pat, ref scrutinee) => {
398 // [opt_ident]: loop {
399 // match <sub_expr> {
404 let scrutinee = self.with_loop_condition_scope(|t| t.lower_expr(scrutinee));
405 let pat = self.lower_pat(pat);
406 (pat, scrutinee, hir::MatchSource::WhileLetDesugar, hir::LoopSource::WhileLet)
409 // We desugar: `'label: while $cond $body` into:
413 // match drop-temps { $cond } {
421 let cond = self.with_loop_condition_scope(|this| this.lower_expr(cond));
423 self.mark_span_with_reason(DesugaringKind::CondTemporary, cond.span, None);
424 // Wrap in a construct equivalent to `{ let _t = $cond; _t }`
425 // to preserve drop semantics since `while cond { ... }` does not
426 // let temporaries live outside of `cond`.
427 let cond = self.expr_drop_temps(span_block, cond, ThinVec::new());
429 let pat = self.pat_bool(span, true);
430 (pat, cond, hir::MatchSource::WhileDesugar, hir::LoopSource::While)
433 let then_arm = self.arm(then_pat, self.arena.alloc(then_expr));
435 // `match <scrutinee> { ... }`
437 self.expr_match(span, scrutinee, arena_vec![self; then_arm, else_arm], desugar);
439 // `[opt_ident]: loop { ... }`
440 hir::ExprKind::Loop(self.block_expr(self.arena.alloc(match_expr)), opt_label, source)
443 /// Desugar `try { <stmts>; <expr> }` into `{ <stmts>; ::std::ops::Try::from_ok(<expr>) }`,
444 /// `try { <stmts>; }` into `{ <stmts>; ::std::ops::Try::from_ok(()) }`
445 /// and save the block id to use it as a break target for desugaring of the `?` operator.
446 fn lower_expr_try_block(&mut self, body: &Block) -> hir::ExprKind<'hir> {
447 self.with_catch_scope(body.id, |this| {
448 let mut block = this.lower_block_noalloc(body, true);
450 // Final expression of the block (if present) or `()` with span at the end of block
451 let (try_span, tail_expr) = if let Some(expr) = block.expr.take() {
453 this.mark_span_with_reason(
454 DesugaringKind::TryBlock,
456 this.allow_try_trait.clone(),
461 let try_span = this.mark_span_with_reason(
462 DesugaringKind::TryBlock,
463 this.sess.source_map().end_point(body.span),
464 this.allow_try_trait.clone(),
467 (try_span, this.expr_unit(try_span))
470 let ok_wrapped_span =
471 this.mark_span_with_reason(DesugaringKind::TryBlock, tail_expr.span, None);
473 // `::std::ops::Try::from_ok($tail_expr)`
474 block.expr = Some(this.wrap_in_try_constructor(
475 hir::LangItem::TryFromOk,
481 hir::ExprKind::Block(this.arena.alloc(block), None)
485 fn wrap_in_try_constructor(
487 lang_item: hir::LangItem,
489 expr: &'hir hir::Expr<'hir>,
491 ) -> &'hir hir::Expr<'hir> {
493 self.arena.alloc(self.expr_lang_item_path(method_span, lang_item, ThinVec::new()));
494 self.expr_call(overall_span, constructor, std::slice::from_ref(expr))
497 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm<'hir> {
499 hir_id: self.next_id(),
500 attrs: self.lower_attrs(&arm.attrs),
501 pat: self.lower_pat(&arm.pat),
502 guard: match arm.guard {
503 Some(ref x) => Some(hir::Guard::If(self.lower_expr(x))),
506 body: self.lower_expr(&arm.body),
511 /// Lower an `async` construct to a generator that is then wrapped so it implements `Future`.
516 /// std::future::from_generator(static move? |_task_context| -> <ret_ty> {
520 pub(super) fn make_async_expr(
522 capture_clause: CaptureBy,
523 closure_node_id: NodeId,
524 ret_ty: Option<AstP<Ty>>,
526 async_gen_kind: hir::AsyncGeneratorKind,
527 body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
528 ) -> hir::ExprKind<'hir> {
529 let output = match ret_ty {
530 Some(ty) => hir::FnRetTy::Return(self.lower_ty(&ty, ImplTraitContext::disallowed())),
531 None => hir::FnRetTy::DefaultReturn(span),
534 // Resume argument type. We let the compiler infer this to simplify the lowering. It is
535 // fully constrained by `future::from_generator`.
536 let input_ty = hir::Ty { hir_id: self.next_id(), kind: hir::TyKind::Infer, 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 { attrs: &[], hir_id: self.next_id(), pat, ty_span: span, span };
553 let params = arena_vec![self; param];
555 let body_id = self.lower_body(move |this| {
556 this.generator_kind = Some(hir::GeneratorKind::Async(async_gen_kind));
558 let old_ctx = this.task_context;
559 this.task_context = Some(task_context_hid);
560 let res = body(this);
561 this.task_context = old_ctx;
565 // `static |_task_context| -> <ret_ty> { body }`:
566 let generator_kind = hir::ExprKind::Closure(
571 Some(hir::Movability::Static),
573 let generator = hir::Expr {
574 hir_id: self.lower_node_id(closure_node_id),
575 kind: generator_kind,
577 attrs: ThinVec::new(),
580 // `future::from_generator`:
582 self.mark_span_with_reason(DesugaringKind::Async, span, self.allow_gen_future.clone());
584 self.expr_lang_item_path(unstable_span, hir::LangItem::FromGenerator, ThinVec::new());
586 // `future::from_generator(generator)`:
587 hir::ExprKind::Call(self.arena.alloc(gen_future), arena_vec![self; generator])
590 /// Desugar `<expr>.await` into:
593 /// mut pinned => loop {
594 /// match unsafe { ::std::future::Future::poll(
595 /// <::std::pin::Pin>::new_unchecked(&mut pinned),
596 /// ::std::future::get_context(task_context),
598 /// ::std::task::Poll::Ready(result) => break result,
599 /// ::std::task::Poll::Pending => {}
601 /// task_context = yield ();
605 fn lower_expr_await(&mut self, await_span: Span, expr: &Expr) -> hir::ExprKind<'hir> {
606 match self.generator_kind {
607 Some(hir::GeneratorKind::Async(_)) => {}
608 Some(hir::GeneratorKind::Gen) | None => {
609 let mut err = struct_span_err!(
613 "`await` is only allowed inside `async` functions and blocks"
615 err.span_label(await_span, "only allowed inside `async` functions and blocks");
616 if let Some(item_sp) = self.current_item {
617 err.span_label(item_sp, "this is not `async`");
622 let span = self.mark_span_with_reason(DesugaringKind::Await, await_span, None);
623 let gen_future_span = self.mark_span_with_reason(
624 DesugaringKind::Await,
626 self.allow_gen_future.clone(),
628 let expr = self.lower_expr(expr);
630 let pinned_ident = Ident::with_dummy_span(sym::pinned);
631 let (pinned_pat, pinned_pat_hid) =
632 self.pat_ident_binding_mode(span, pinned_ident, hir::BindingAnnotation::Mutable);
634 let task_context_ident = Ident::with_dummy_span(sym::_task_context);
637 // ::std::future::Future::poll(
638 // ::std::pin::Pin::new_unchecked(&mut pinned),
639 // ::std::future::get_context(task_context),
643 let pinned = self.expr_ident(span, pinned_ident, pinned_pat_hid);
644 let ref_mut_pinned = self.expr_mut_addr_of(span, pinned);
645 let task_context = if let Some(task_context_hid) = self.task_context {
646 self.expr_ident_mut(span, task_context_ident, task_context_hid)
648 // Use of `await` outside of an async context, we cannot use `task_context` here.
651 let new_unchecked = self.expr_call_lang_item_fn_mut(
653 hir::LangItem::PinNewUnchecked,
654 arena_vec![self; ref_mut_pinned],
656 let get_context = self.expr_call_lang_item_fn_mut(
658 hir::LangItem::GetContext,
659 arena_vec![self; task_context],
661 let call = self.expr_call_lang_item_fn(
663 hir::LangItem::FuturePoll,
664 arena_vec![self; new_unchecked, get_context],
666 self.arena.alloc(self.expr_unsafe(call))
669 // `::std::task::Poll::Ready(result) => break result`
670 let loop_node_id = self.resolver.next_node_id();
671 let loop_hir_id = self.lower_node_id(loop_node_id);
673 let x_ident = Ident::with_dummy_span(sym::result);
674 let (x_pat, x_pat_hid) = self.pat_ident(span, x_ident);
675 let x_expr = self.expr_ident(span, x_ident, x_pat_hid);
676 let ready_field = self.single_pat_field(span, x_pat);
677 let ready_pat = self.pat_lang_item_variant(span, hir::LangItem::PollReady, ready_field);
678 let break_x = self.with_loop_scope(loop_node_id, move |this| {
680 hir::ExprKind::Break(this.lower_loop_destination(None), Some(x_expr));
681 this.arena.alloc(this.expr(await_span, expr_break, ThinVec::new()))
683 self.arm(ready_pat, break_x)
686 // `::std::task::Poll::Pending => {}`
688 let pending_pat = self.pat_lang_item_variant(span, hir::LangItem::PollPending, &[]);
689 let empty_block = self.expr_block_empty(span);
690 self.arm(pending_pat, empty_block)
693 let inner_match_stmt = {
694 let match_expr = self.expr_match(
697 arena_vec![self; ready_arm, pending_arm],
698 hir::MatchSource::AwaitDesugar,
700 self.stmt_expr(span, match_expr)
703 // task_context = yield ();
705 let unit = self.expr_unit(span);
706 let yield_expr = self.expr(
708 hir::ExprKind::Yield(unit, hir::YieldSource::Await { expr: Some(expr.hir_id) }),
711 let yield_expr = self.arena.alloc(yield_expr);
713 if let Some(task_context_hid) = self.task_context {
714 let lhs = self.expr_ident(span, task_context_ident, task_context_hid);
716 self.expr(span, hir::ExprKind::Assign(lhs, yield_expr, span), AttrVec::new());
717 self.stmt_expr(span, assign)
719 // Use of `await` outside of an async context. Return `yield_expr` so that we can
720 // proceed with type checking.
721 self.stmt(span, hir::StmtKind::Semi(yield_expr))
725 let loop_block = self.block_all(span, arena_vec![self; inner_match_stmt, yield_stmt], None);
728 let loop_expr = self.arena.alloc(hir::Expr {
730 kind: hir::ExprKind::Loop(loop_block, None, hir::LoopSource::Loop),
732 attrs: ThinVec::new(),
735 // mut pinned => loop { ... }
736 let pinned_arm = self.arm(pinned_pat, loop_expr);
739 // mut pinned => loop { .. }
741 hir::ExprKind::Match(expr, arena_vec![self; pinned_arm], hir::MatchSource::AwaitDesugar)
744 fn lower_expr_closure(
746 capture_clause: CaptureBy,
747 movability: Movability,
751 ) -> hir::ExprKind<'hir> {
752 // Lower outside new scope to preserve `is_in_loop_condition`.
753 let fn_decl = self.lower_fn_decl(decl, None, false, None);
755 self.with_new_scopes(move |this| {
756 let prev = this.current_item;
757 this.current_item = Some(fn_decl_span);
758 let mut generator_kind = None;
759 let body_id = this.lower_fn_body(decl, |this| {
760 let e = this.lower_expr_mut(body);
761 generator_kind = this.generator_kind;
764 let generator_option =
765 this.generator_movability_for_fn(&decl, fn_decl_span, generator_kind, movability);
766 this.current_item = prev;
767 hir::ExprKind::Closure(capture_clause, fn_decl, body_id, fn_decl_span, generator_option)
771 fn generator_movability_for_fn(
775 generator_kind: Option<hir::GeneratorKind>,
776 movability: Movability,
777 ) -> Option<hir::Movability> {
778 match generator_kind {
779 Some(hir::GeneratorKind::Gen) => {
780 if decl.inputs.len() > 1 {
785 "too many parameters for a generator (expected 0 or 1 parameters)"
791 Some(hir::GeneratorKind::Async(_)) => {
792 panic!("non-`async` closure body turned `async` during lowering");
795 if movability == Movability::Static {
796 struct_span_err!(self.sess, fn_decl_span, E0697, "closures cannot be static")
804 fn lower_expr_async_closure(
806 capture_clause: CaptureBy,
811 ) -> hir::ExprKind<'hir> {
813 FnDecl { inputs: decl.inputs.clone(), output: FnRetTy::Default(fn_decl_span) };
814 // We need to lower the declaration outside the new scope, because we
815 // have to conserve the state of being inside a loop condition for the
816 // closure argument types.
817 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
819 self.with_new_scopes(move |this| {
820 // FIXME(cramertj): allow `async` non-`move` closures with arguments.
821 if capture_clause == CaptureBy::Ref && !decl.inputs.is_empty() {
826 "`async` non-`move` closures with parameters are not currently supported",
829 "consider using `let` statements to manually capture \
830 variables by reference before entering an `async move` closure",
835 // Transform `async |x: u8| -> X { ... }` into
836 // `|x: u8| future_from_generator(|| -> X { ... })`.
837 let body_id = this.lower_fn_body(&outer_decl, |this| {
839 if let FnRetTy::Ty(ty) = &decl.output { Some(ty.clone()) } else { None };
840 let async_body = this.make_async_expr(
845 hir::AsyncGeneratorKind::Closure,
846 |this| this.with_new_scopes(|this| this.lower_expr_mut(body)),
848 this.expr(fn_decl_span, async_body, ThinVec::new())
850 hir::ExprKind::Closure(capture_clause, fn_decl, body_id, fn_decl_span, None)
854 /// Destructure the LHS of complex assignments.
855 /// For instance, lower `(a, b) = t` to `{ let (lhs1, lhs2) = t; a = lhs1; b = lhs2; }`.
856 fn lower_expr_assign(
862 ) -> hir::ExprKind<'hir> {
863 // Return early in case of an ordinary assignment.
864 fn is_ordinary(lower_ctx: &mut LoweringContext<'_, '_>, lhs: &Expr) -> bool {
866 ExprKind::Array(..) | ExprKind::Struct(..) | ExprKind::Tup(..) => false,
867 // Check for tuple struct constructor.
868 ExprKind::Call(callee, ..) => lower_ctx.extract_tuple_struct_path(callee).is_none(),
869 ExprKind::Paren(e) => {
871 // We special-case `(..)` for consistency with patterns.
872 ExprKind::Range(None, None, RangeLimits::HalfOpen) => false,
873 _ => is_ordinary(lower_ctx, e),
879 if is_ordinary(self, lhs) {
880 return hir::ExprKind::Assign(self.lower_expr(lhs), self.lower_expr(rhs), eq_sign_span);
882 if !self.sess.features_untracked().destructuring_assignment {
884 &self.sess.parse_sess,
885 sym::destructuring_assignment,
887 "destructuring assignments are unstable",
889 .span_label(lhs.span, "cannot assign to this expression")
893 let mut assignments = vec![];
895 // The LHS becomes a pattern: `(lhs1, lhs2)`.
896 let pat = self.destructure_assign(lhs, eq_sign_span, &mut assignments);
897 let rhs = self.lower_expr(rhs);
899 // Introduce a `let` for destructuring: `let (lhs1, lhs2) = t`.
900 let destructure_let = self.stmt_let_pat(
905 hir::LocalSource::AssignDesugar(eq_sign_span),
908 // `a = lhs1; b = lhs2;`.
911 .alloc_from_iter(std::iter::once(destructure_let).chain(assignments.into_iter()));
913 // Wrap everything in a block.
914 hir::ExprKind::Block(&self.block_all(whole_span, stmts, None), None)
917 /// If the given expression is a path to a tuple struct, returns that path.
918 /// It is not a complete check, but just tries to reject most paths early
919 /// if they are not tuple structs.
920 /// Type checking will take care of the full validation later.
921 fn extract_tuple_struct_path<'a>(&mut self, expr: &'a Expr) -> Option<&'a Path> {
922 // For tuple struct destructuring, it must be a non-qualified path (like in patterns).
923 if let ExprKind::Path(None, path) = &expr.kind {
924 // Does the path resolves to something disallowed in a tuple struct/variant pattern?
925 if let Some(partial_res) = self.resolver.get_partial_res(expr.id) {
926 if partial_res.unresolved_segments() == 0
927 && !partial_res.base_res().expected_in_tuple_struct_pat()
937 /// Convert the LHS of a destructuring assignment to a pattern.
938 /// Each sub-assignment is recorded in `assignments`.
939 fn destructure_assign(
943 assignments: &mut Vec<hir::Stmt<'hir>>,
944 ) -> &'hir hir::Pat<'hir> {
947 ExprKind::Array(elements) => {
949 self.destructure_sequence(elements, "slice", eq_sign_span, assignments);
950 let slice_pat = if let Some((i, span)) = rest {
951 let (before, after) = pats.split_at(i);
954 Some(self.pat_without_dbm(span, hir::PatKind::Wild)),
958 hir::PatKind::Slice(pats, None, &[])
960 return self.pat_without_dbm(lhs.span, slice_pat);
963 ExprKind::Call(callee, args) => {
964 if let Some(path) = self.extract_tuple_struct_path(callee) {
965 let (pats, rest) = self.destructure_sequence(
967 "tuple struct or variant",
971 let qpath = self.lower_qpath(
976 ImplTraitContext::disallowed(),
978 // Destructure like a tuple struct.
979 let tuple_struct_pat =
980 hir::PatKind::TupleStruct(qpath, pats, rest.map(|r| r.0));
981 return self.pat_without_dbm(lhs.span, tuple_struct_pat);
985 ExprKind::Struct(path, fields, rest) => {
986 let field_pats = self.arena.alloc_from_iter(fields.iter().map(|f| {
987 let pat = self.destructure_assign(&f.expr, eq_sign_span, assignments);
989 hir_id: self.next_id(),
992 is_shorthand: f.is_shorthand,
996 let qpath = self.lower_qpath(
1000 ParamMode::Optional,
1001 ImplTraitContext::disallowed(),
1003 let fields_omitted = match rest {
1004 StructRest::Base(e) => {
1008 "functional record updates are not allowed in destructuring \
1013 "consider removing the trailing pattern",
1015 rustc_errors::Applicability::MachineApplicable,
1020 StructRest::Rest(_) => true,
1021 StructRest::None => false,
1023 let struct_pat = hir::PatKind::Struct(qpath, field_pats, fields_omitted);
1024 return self.pat_without_dbm(lhs.span, struct_pat);
1027 ExprKind::Tup(elements) => {
1029 self.destructure_sequence(elements, "tuple", eq_sign_span, assignments);
1030 let tuple_pat = hir::PatKind::Tuple(pats, rest.map(|r| r.0));
1031 return self.pat_without_dbm(lhs.span, tuple_pat);
1033 ExprKind::Paren(e) => {
1034 // We special-case `(..)` for consistency with patterns.
1035 if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
1036 let tuple_pat = hir::PatKind::Tuple(&[], Some(0));
1037 return self.pat_without_dbm(lhs.span, tuple_pat);
1039 return self.destructure_assign(e, eq_sign_span, assignments);
1044 // Treat all other cases as normal lvalue.
1045 let ident = Ident::new(sym::lhs, lhs.span);
1046 let (pat, binding) = self.pat_ident(lhs.span, ident);
1047 let ident = self.expr_ident(lhs.span, ident, binding);
1048 let assign = hir::ExprKind::Assign(self.lower_expr(lhs), ident, eq_sign_span);
1049 let expr = self.expr(lhs.span, assign, ThinVec::new());
1050 assignments.push(self.stmt_expr(lhs.span, expr));
1054 /// Destructure a sequence of expressions occurring on the LHS of an assignment.
1055 /// Such a sequence occurs in a tuple (struct)/slice.
1056 /// Return a sequence of corresponding patterns, and the index and the span of `..` if it
1058 /// Each sub-assignment is recorded in `assignments`.
1059 fn destructure_sequence(
1061 elements: &[AstP<Expr>],
1064 assignments: &mut Vec<hir::Stmt<'hir>>,
1065 ) -> (&'hir [&'hir hir::Pat<'hir>], Option<(usize, Span)>) {
1066 let mut rest = None;
1068 self.arena.alloc_from_iter(elements.iter().enumerate().filter_map(|(i, e)| {
1069 // Check for `..` pattern.
1070 if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
1071 if let Some((_, prev_span)) = rest {
1072 self.ban_extra_rest_pat(e.span, prev_span, ctx);
1074 rest = Some((i, e.span));
1078 Some(self.destructure_assign(e, eq_sign_span, assignments))
1084 /// Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`.
1085 fn lower_expr_range_closed(&mut self, span: Span, e1: &Expr, e2: &Expr) -> hir::ExprKind<'hir> {
1086 let e1 = self.lower_expr_mut(e1);
1087 let e2 = self.lower_expr_mut(e2);
1088 let fn_path = hir::QPath::LangItem(hir::LangItem::RangeInclusiveNew, span);
1090 self.arena.alloc(self.expr(span, hir::ExprKind::Path(fn_path), ThinVec::new()));
1091 hir::ExprKind::Call(fn_expr, arena_vec![self; e1, e2])
1094 fn lower_expr_range(
1100 ) -> hir::ExprKind<'hir> {
1101 use rustc_ast::RangeLimits::*;
1103 let lang_item = match (e1, e2, lims) {
1104 (None, None, HalfOpen) => hir::LangItem::RangeFull,
1105 (Some(..), None, HalfOpen) => hir::LangItem::RangeFrom,
1106 (None, Some(..), HalfOpen) => hir::LangItem::RangeTo,
1107 (Some(..), Some(..), HalfOpen) => hir::LangItem::Range,
1108 (None, Some(..), Closed) => hir::LangItem::RangeToInclusive,
1109 (Some(..), Some(..), Closed) => unreachable!(),
1110 (_, None, Closed) => {
1111 self.diagnostic().span_fatal(span, "inclusive range with no end").raise()
1115 let fields = self.arena.alloc_from_iter(
1116 e1.iter().map(|e| ("start", e)).chain(e2.iter().map(|e| ("end", e))).map(|(s, e)| {
1117 let expr = self.lower_expr(&e);
1118 let ident = Ident::new(Symbol::intern(s), e.span);
1119 self.field(ident, expr, e.span)
1123 hir::ExprKind::Struct(self.arena.alloc(hir::QPath::LangItem(lang_item, span)), fields, None)
1126 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
1127 let target_id = match destination {
1129 if let Some(loop_id) = self.resolver.get_label_res(id) {
1130 Ok(self.lower_node_id(loop_id))
1132 Err(hir::LoopIdError::UnresolvedLabel)
1139 .map(|id| Ok(self.lower_node_id(id)))
1140 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope)),
1142 hir::Destination { label: destination.map(|(_, label)| label), target_id }
1145 fn lower_jump_destination(&mut self, id: NodeId, opt_label: Option<Label>) -> hir::Destination {
1146 if self.is_in_loop_condition && opt_label.is_none() {
1149 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition),
1152 self.lower_loop_destination(opt_label.map(|label| (id, label)))
1156 fn with_catch_scope<T>(&mut self, catch_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1157 let len = self.catch_scopes.len();
1158 self.catch_scopes.push(catch_id);
1160 let result = f(self);
1163 self.catch_scopes.len(),
1164 "catch scopes should be added and removed in stack order"
1167 self.catch_scopes.pop().unwrap();
1172 fn with_loop_scope<T>(&mut self, loop_id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1173 // We're no longer in the base loop's condition; we're in another loop.
1174 let was_in_loop_condition = self.is_in_loop_condition;
1175 self.is_in_loop_condition = false;
1177 let len = self.loop_scopes.len();
1178 self.loop_scopes.push(loop_id);
1180 let result = f(self);
1183 self.loop_scopes.len(),
1184 "loop scopes should be added and removed in stack order"
1187 self.loop_scopes.pop().unwrap();
1189 self.is_in_loop_condition = was_in_loop_condition;
1194 fn with_loop_condition_scope<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
1195 let was_in_loop_condition = self.is_in_loop_condition;
1196 self.is_in_loop_condition = true;
1198 let result = f(self);
1200 self.is_in_loop_condition = was_in_loop_condition;
1205 fn lower_expr_asm(&mut self, sp: Span, asm: &InlineAsm) -> hir::ExprKind<'hir> {
1206 if self.sess.asm_arch.is_none() {
1207 struct_span_err!(self.sess, sp, E0472, "asm! is unsupported on this target").emit();
1209 if asm.options.contains(InlineAsmOptions::ATT_SYNTAX)
1212 Some(asm::InlineAsmArch::X86 | asm::InlineAsmArch::X86_64)
1216 .struct_span_err(sp, "the `att_syntax` option is only supported on x86")
1220 // Lower operands to HIR, filter_map skips any operands with invalid
1221 // register classes.
1222 let sess = self.sess;
1223 let operands: Vec<_> = asm
1226 .filter_map(|(op, op_sp)| {
1227 let lower_reg = |reg| {
1229 InlineAsmRegOrRegClass::Reg(s) => asm::InlineAsmRegOrRegClass::Reg(
1230 asm::InlineAsmReg::parse(
1232 |feature| sess.target_features.contains(&Symbol::intern(feature)),
1237 let msg = format!("invalid register `{}`: {}", s.as_str(), e);
1238 sess.struct_span_err(*op_sp, &msg).emit();
1242 InlineAsmRegOrRegClass::RegClass(s) => {
1243 asm::InlineAsmRegOrRegClass::RegClass(
1244 asm::InlineAsmRegClass::parse(sess.asm_arch?, s)
1247 "invalid register class `{}`: {}",
1251 sess.struct_span_err(*op_sp, &msg).emit();
1259 // lower_reg is executed last because we need to lower all
1260 // sub-expressions even if we throw them away later.
1261 let op = match *op {
1262 InlineAsmOperand::In { reg, ref expr } => hir::InlineAsmOperand::In {
1263 expr: self.lower_expr_mut(expr),
1264 reg: lower_reg(reg)?,
1266 InlineAsmOperand::Out { reg, late, ref expr } => hir::InlineAsmOperand::Out {
1268 expr: expr.as_ref().map(|expr| self.lower_expr_mut(expr)),
1269 reg: lower_reg(reg)?,
1271 InlineAsmOperand::InOut { reg, late, ref expr } => {
1272 hir::InlineAsmOperand::InOut {
1274 expr: self.lower_expr_mut(expr),
1275 reg: lower_reg(reg)?,
1278 InlineAsmOperand::SplitInOut { reg, late, ref in_expr, ref out_expr } => {
1279 hir::InlineAsmOperand::SplitInOut {
1281 in_expr: self.lower_expr_mut(in_expr),
1282 out_expr: out_expr.as_ref().map(|expr| self.lower_expr_mut(expr)),
1283 reg: lower_reg(reg)?,
1286 InlineAsmOperand::Const { ref expr } => {
1287 hir::InlineAsmOperand::Const { expr: self.lower_expr_mut(expr) }
1289 InlineAsmOperand::Sym { ref expr } => {
1290 hir::InlineAsmOperand::Sym { expr: self.lower_expr_mut(expr) }
1297 // Stop if there were any errors when lowering the register classes
1298 if operands.len() != asm.operands.len() || sess.asm_arch.is_none() {
1299 return hir::ExprKind::Err;
1302 // Validate template modifiers against the register classes for the operands
1303 let asm_arch = sess.asm_arch.unwrap();
1304 for p in &asm.template {
1305 if let InlineAsmTemplatePiece::Placeholder {
1307 modifier: Some(modifier),
1308 span: placeholder_span,
1311 let op_sp = asm.operands[operand_idx].1;
1312 match &operands[operand_idx] {
1313 hir::InlineAsmOperand::In { reg, .. }
1314 | hir::InlineAsmOperand::Out { reg, .. }
1315 | hir::InlineAsmOperand::InOut { reg, .. }
1316 | hir::InlineAsmOperand::SplitInOut { reg, .. } => {
1317 let class = reg.reg_class();
1318 let valid_modifiers = class.valid_modifiers(asm_arch);
1319 if !valid_modifiers.contains(&modifier) {
1320 let mut err = sess.struct_span_err(
1322 "invalid asm template modifier for this register class",
1324 err.span_label(placeholder_span, "template modifier");
1325 err.span_label(op_sp, "argument");
1326 if !valid_modifiers.is_empty() {
1327 let mut mods = format!("`{}`", valid_modifiers[0]);
1328 for m in &valid_modifiers[1..] {
1329 let _ = write!(mods, ", `{}`", m);
1332 "the `{}` register class supports \
1333 the following template modifiers: {}",
1339 "the `{}` register class does not support template modifiers",
1346 hir::InlineAsmOperand::Const { .. } => {
1347 let mut err = sess.struct_span_err(
1349 "asm template modifiers are not allowed for `const` arguments",
1351 err.span_label(placeholder_span, "template modifier");
1352 err.span_label(op_sp, "argument");
1355 hir::InlineAsmOperand::Sym { .. } => {
1356 let mut err = sess.struct_span_err(
1358 "asm template modifiers are not allowed for `sym` arguments",
1360 err.span_label(placeholder_span, "template modifier");
1361 err.span_label(op_sp, "argument");
1368 let mut used_input_regs = FxHashMap::default();
1369 let mut used_output_regs = FxHashMap::default();
1370 for (idx, op) in operands.iter().enumerate() {
1371 let op_sp = asm.operands[idx].1;
1372 if let Some(reg) = op.reg() {
1373 // Validate register classes against currently enabled target
1374 // features. We check that at least one type is available for
1375 // the current target.
1376 let reg_class = reg.reg_class();
1377 let mut required_features: Vec<&str> = vec![];
1378 for &(_, feature) in reg_class.supported_types(asm_arch) {
1379 if let Some(feature) = feature {
1380 if self.sess.target_features.contains(&Symbol::intern(feature)) {
1381 required_features.clear();
1384 required_features.push(feature);
1387 required_features.clear();
1391 // We are sorting primitive strs here and can use unstable sort here
1392 required_features.sort_unstable();
1393 required_features.dedup();
1394 match &required_features[..] {
1398 "register class `{}` requires the `{}` target feature",
1402 sess.struct_span_err(op_sp, &msg).emit();
1406 "register class `{}` requires at least one target feature: {}",
1410 sess.struct_span_err(op_sp, &msg).emit();
1414 // Check for conflicts between explicit register operands.
1415 if let asm::InlineAsmRegOrRegClass::Reg(reg) = reg {
1416 let (input, output) = match op {
1417 hir::InlineAsmOperand::In { .. } => (true, false),
1418 // Late output do not conflict with inputs, but normal outputs do
1419 hir::InlineAsmOperand::Out { late, .. } => (!late, true),
1420 hir::InlineAsmOperand::InOut { .. }
1421 | hir::InlineAsmOperand::SplitInOut { .. } => (true, true),
1422 hir::InlineAsmOperand::Const { .. } | hir::InlineAsmOperand::Sym { .. } => {
1427 // Flag to output the error only once per operand
1428 let mut skip = false;
1429 reg.overlapping_regs(|r| {
1430 let mut check = |used_regs: &mut FxHashMap<asm::InlineAsmReg, usize>,
1432 match used_regs.entry(r) {
1433 Entry::Occupied(o) => {
1439 let idx2 = *o.get();
1440 let op2 = &operands[idx2];
1441 let op_sp2 = asm.operands[idx2].1;
1442 let reg2 = match op2.reg() {
1443 Some(asm::InlineAsmRegOrRegClass::Reg(r)) => r,
1444 _ => unreachable!(),
1448 "register `{}` conflicts with register `{}`",
1452 let mut err = sess.struct_span_err(op_sp, &msg);
1453 err.span_label(op_sp, &format!("register `{}`", reg.name()));
1454 err.span_label(op_sp2, &format!("register `{}`", reg2.name()));
1458 hir::InlineAsmOperand::In { .. },
1459 hir::InlineAsmOperand::Out { late, .. },
1462 hir::InlineAsmOperand::Out { late, .. },
1463 hir::InlineAsmOperand::In { .. },
1466 let out_op_sp = if input { op_sp2 } else { op_sp };
1467 let msg = "use `lateout` instead of \
1468 `out` to avoid conflict";
1469 err.span_help(out_op_sp, msg);
1476 Entry::Vacant(v) => {
1482 check(&mut used_input_regs, true);
1485 check(&mut used_output_regs, false);
1492 let operands = self.arena.alloc_from_iter(operands);
1493 let template = self.arena.alloc_from_iter(asm.template.iter().cloned());
1494 let line_spans = self.arena.alloc_slice(&asm.line_spans[..]);
1495 let hir_asm = hir::InlineAsm { template, operands, options: asm.options, line_spans };
1496 hir::ExprKind::InlineAsm(self.arena.alloc(hir_asm))
1499 fn lower_expr_llvm_asm(&mut self, asm: &LlvmInlineAsm) -> hir::ExprKind<'hir> {
1500 let inner = hir::LlvmInlineAsmInner {
1501 inputs: asm.inputs.iter().map(|&(c, _)| c).collect(),
1505 .map(|out| hir::LlvmInlineAsmOutput {
1506 constraint: out.constraint,
1508 is_indirect: out.is_indirect,
1509 span: out.expr.span,
1513 asm_str_style: asm.asm_str_style,
1514 clobbers: asm.clobbers.clone(),
1515 volatile: asm.volatile,
1516 alignstack: asm.alignstack,
1517 dialect: asm.dialect,
1519 let hir_asm = hir::LlvmInlineAsm {
1521 inputs_exprs: self.arena.alloc_from_iter(
1522 asm.inputs.iter().map(|&(_, ref input)| self.lower_expr_mut(input)),
1526 .alloc_from_iter(asm.outputs.iter().map(|out| self.lower_expr_mut(&out.expr))),
1528 hir::ExprKind::LlvmInlineAsm(self.arena.alloc(hir_asm))
1531 fn lower_field(&mut self, f: &Field) -> hir::Field<'hir> {
1533 hir_id: self.next_id(),
1535 expr: self.lower_expr(&f.expr),
1537 is_shorthand: f.is_shorthand,
1541 fn lower_expr_yield(&mut self, span: Span, opt_expr: Option<&Expr>) -> hir::ExprKind<'hir> {
1542 match self.generator_kind {
1543 Some(hir::GeneratorKind::Gen) => {}
1544 Some(hir::GeneratorKind::Async(_)) => {
1549 "`async` generators are not yet supported"
1553 None => self.generator_kind = Some(hir::GeneratorKind::Gen),
1557 opt_expr.as_ref().map(|x| self.lower_expr(x)).unwrap_or_else(|| self.expr_unit(span));
1559 hir::ExprKind::Yield(expr, hir::YieldSource::Yield)
1562 /// Desugar `ExprForLoop` from: `[opt_ident]: for <pat> in <head> <body>` into:
1565 /// let result = match ::std::iter::IntoIterator::into_iter(<head>) {
1567 /// [opt_ident]: loop {
1569 /// match ::std::iter::Iterator::next(&mut iter) {
1570 /// ::std::option::Option::Some(val) => __next = val,
1571 /// ::std::option::Option::None => break
1573 /// let <pat> = __next;
1574 /// StmtKind::Expr(<body>);
1587 opt_label: Option<Label>,
1588 ) -> hir::Expr<'hir> {
1589 let orig_head_span = head.span;
1591 let mut head = self.lower_expr_mut(head);
1592 let desugared_span = self.mark_span_with_reason(
1593 DesugaringKind::ForLoop(ForLoopLoc::Head),
1597 head.span = desugared_span;
1599 let iter = Ident::with_dummy_span(sym::iter);
1601 let next_ident = Ident::with_dummy_span(sym::__next);
1602 let (next_pat, next_pat_hid) = self.pat_ident_binding_mode(
1605 hir::BindingAnnotation::Mutable,
1608 // `::std::option::Option::Some(val) => __next = val`
1610 let val_ident = Ident::with_dummy_span(sym::val);
1611 let (val_pat, val_pat_hid) = self.pat_ident(pat.span, val_ident);
1612 let val_expr = self.expr_ident(pat.span, val_ident, val_pat_hid);
1613 let next_expr = self.expr_ident(pat.span, next_ident, next_pat_hid);
1614 let assign = self.arena.alloc(self.expr(
1616 hir::ExprKind::Assign(next_expr, val_expr, pat.span),
1619 let some_pat = self.pat_some(pat.span, val_pat);
1620 self.arm(some_pat, assign)
1623 // `::std::option::Option::None => break`
1626 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
1627 let pat = self.pat_none(e.span);
1628 self.arm(pat, break_expr)
1632 let (iter_pat, iter_pat_nid) =
1633 self.pat_ident_binding_mode(desugared_span, iter, hir::BindingAnnotation::Mutable);
1635 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
1637 let iter = self.expr_ident(desugared_span, iter, iter_pat_nid);
1638 let ref_mut_iter = self.expr_mut_addr_of(desugared_span, iter);
1639 let next_expr = self.expr_call_lang_item_fn(
1641 hir::LangItem::IteratorNext,
1642 arena_vec![self; ref_mut_iter],
1644 let arms = arena_vec![self; pat_arm, break_arm];
1646 self.expr_match(desugared_span, next_expr, arms, hir::MatchSource::ForLoopDesugar)
1648 let match_stmt = self.stmt_expr(desugared_span, match_expr);
1650 let next_expr = self.expr_ident(desugared_span, next_ident, next_pat_hid);
1653 let next_let = self.stmt_let_pat(
1658 hir::LocalSource::ForLoopDesugar,
1661 // `let <pat> = __next`
1662 let pat = self.lower_pat(pat);
1663 let pat_let = self.stmt_let_pat(
1668 hir::LocalSource::ForLoopDesugar,
1671 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
1672 let body_expr = self.expr_block(body_block, ThinVec::new());
1673 let body_stmt = self.stmt_expr(body.span, body_expr);
1675 let loop_block = self.block_all(
1677 arena_vec![self; next_let, match_stmt, pat_let, body_stmt],
1681 // `[opt_ident]: loop { ... }`
1682 let kind = hir::ExprKind::Loop(loop_block, opt_label, hir::LoopSource::ForLoop);
1683 let loop_expr = self.arena.alloc(hir::Expr {
1684 hir_id: self.lower_node_id(e.id),
1687 attrs: ThinVec::new(),
1690 // `mut iter => { ... }`
1691 let iter_arm = self.arm(iter_pat, loop_expr);
1693 let into_iter_span = self.mark_span_with_reason(
1694 DesugaringKind::ForLoop(ForLoopLoc::IntoIter),
1699 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
1700 let into_iter_expr = {
1701 self.expr_call_lang_item_fn(
1703 hir::LangItem::IntoIterIntoIter,
1704 arena_vec![self; head],
1708 let match_expr = self.arena.alloc(self.expr_match(
1711 arena_vec![self; iter_arm],
1712 hir::MatchSource::ForLoopDesugar,
1715 let attrs: Vec<_> = e.attrs.iter().map(|a| self.lower_attr(a)).collect();
1717 // This is effectively `{ let _result = ...; _result }`.
1718 // The construct was introduced in #21984 and is necessary to make sure that
1719 // temporaries in the `head` expression are dropped and do not leak to the
1720 // surrounding scope of the `match` since the `match` is not a terminating scope.
1722 // Also, add the attributes to the outer returned expr node.
1723 self.expr_drop_temps_mut(desugared_span, match_expr, attrs.into())
1726 /// Desugar `ExprKind::Try` from: `<expr>?` into:
1728 /// match Try::into_result(<expr>) {
1729 /// Ok(val) => #[allow(unreachable_code)] val,
1730 /// Err(err) => #[allow(unreachable_code)]
1731 /// // If there is an enclosing `try {...}`:
1732 /// break 'catch_target Try::from_error(From::from(err)),
1734 /// return Try::from_error(From::from(err)),
1737 fn lower_expr_try(&mut self, span: Span, sub_expr: &Expr) -> hir::ExprKind<'hir> {
1738 let unstable_span = self.mark_span_with_reason(
1739 DesugaringKind::QuestionMark,
1741 self.allow_try_trait.clone(),
1743 let try_span = self.sess.source_map().end_point(span);
1744 let try_span = self.mark_span_with_reason(
1745 DesugaringKind::QuestionMark,
1747 self.allow_try_trait.clone(),
1750 // `Try::into_result(<expr>)`
1753 let sub_expr = self.lower_expr_mut(sub_expr);
1755 self.expr_call_lang_item_fn(
1757 hir::LangItem::TryIntoResult,
1758 arena_vec![self; sub_expr],
1762 // `#[allow(unreachable_code)]`
1764 // `allow(unreachable_code)`
1766 let allow_ident = Ident::new(sym::allow, span);
1767 let uc_ident = Ident::new(sym::unreachable_code, span);
1768 let uc_nested = attr::mk_nested_word_item(uc_ident);
1769 attr::mk_list_item(allow_ident, vec![uc_nested])
1771 attr::mk_attr_outer(allow)
1773 let attrs = vec![attr];
1775 // `Ok(val) => #[allow(unreachable_code)] val,`
1777 let val_ident = Ident::with_dummy_span(sym::val);
1778 let (val_pat, val_pat_nid) = self.pat_ident(span, val_ident);
1779 let val_expr = self.arena.alloc(self.expr_ident_with_attrs(
1783 ThinVec::from(attrs.clone()),
1785 let ok_pat = self.pat_ok(span, val_pat);
1786 self.arm(ok_pat, val_expr)
1789 // `Err(err) => #[allow(unreachable_code)]
1790 // return Try::from_error(From::from(err)),`
1792 let err_ident = Ident::with_dummy_span(sym::err);
1793 let (err_local, err_local_nid) = self.pat_ident(try_span, err_ident);
1795 let err_expr = self.expr_ident_mut(try_span, err_ident, err_local_nid);
1796 self.expr_call_lang_item_fn(
1798 hir::LangItem::FromFrom,
1799 arena_vec![self; err_expr],
1802 let from_err_expr = self.wrap_in_try_constructor(
1803 hir::LangItem::TryFromError,
1808 let thin_attrs = ThinVec::from(attrs);
1809 let catch_scope = self.catch_scopes.last().copied();
1810 let ret_expr = if let Some(catch_node) = catch_scope {
1811 let target_id = Ok(self.lower_node_id(catch_node));
1812 self.arena.alloc(self.expr(
1814 hir::ExprKind::Break(
1815 hir::Destination { label: None, target_id },
1816 Some(from_err_expr),
1821 self.arena.alloc(self.expr(
1823 hir::ExprKind::Ret(Some(from_err_expr)),
1828 let err_pat = self.pat_err(try_span, err_local);
1829 self.arm(err_pat, ret_expr)
1832 hir::ExprKind::Match(
1834 arena_vec![self; err_arm, ok_arm],
1835 hir::MatchSource::TryDesugar,
1839 // =========================================================================
1840 // Helper methods for building HIR.
1841 // =========================================================================
1843 /// Constructs a `true` or `false` literal expression.
1844 pub(super) fn expr_bool(&mut self, span: Span, val: bool) -> &'hir hir::Expr<'hir> {
1845 let lit = Spanned { span, node: LitKind::Bool(val) };
1846 self.arena.alloc(self.expr(span, hir::ExprKind::Lit(lit), ThinVec::new()))
1849 /// Wrap the given `expr` in a terminating scope using `hir::ExprKind::DropTemps`.
1851 /// In terms of drop order, it has the same effect as wrapping `expr` in
1852 /// `{ let _t = $expr; _t }` but should provide better compile-time performance.
1854 /// The drop order can be important in e.g. `if expr { .. }`.
1855 pub(super) fn expr_drop_temps(
1858 expr: &'hir hir::Expr<'hir>,
1860 ) -> &'hir hir::Expr<'hir> {
1861 self.arena.alloc(self.expr_drop_temps_mut(span, expr, attrs))
1864 pub(super) fn expr_drop_temps_mut(
1867 expr: &'hir hir::Expr<'hir>,
1869 ) -> hir::Expr<'hir> {
1870 self.expr(span, hir::ExprKind::DropTemps(expr), attrs)
1876 arg: &'hir hir::Expr<'hir>,
1877 arms: &'hir [hir::Arm<'hir>],
1878 source: hir::MatchSource,
1879 ) -> hir::Expr<'hir> {
1880 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
1883 fn expr_break(&mut self, span: Span, attrs: AttrVec) -> &'hir hir::Expr<'hir> {
1884 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
1885 self.arena.alloc(self.expr(span, expr_break, attrs))
1888 fn expr_mut_addr_of(&mut self, span: Span, e: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
1891 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Mut, e),
1896 fn expr_unit(&mut self, sp: Span) -> &'hir hir::Expr<'hir> {
1897 self.arena.alloc(self.expr(sp, hir::ExprKind::Tup(&[]), ThinVec::new()))
1903 e: &'hir hir::Expr<'hir>,
1904 args: &'hir [hir::Expr<'hir>],
1905 ) -> hir::Expr<'hir> {
1906 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
1912 e: &'hir hir::Expr<'hir>,
1913 args: &'hir [hir::Expr<'hir>],
1914 ) -> &'hir hir::Expr<'hir> {
1915 self.arena.alloc(self.expr_call_mut(span, e, args))
1918 fn expr_call_lang_item_fn_mut(
1921 lang_item: hir::LangItem,
1922 args: &'hir [hir::Expr<'hir>],
1923 ) -> hir::Expr<'hir> {
1924 let path = self.arena.alloc(self.expr_lang_item_path(span, lang_item, ThinVec::new()));
1925 self.expr_call_mut(span, path, args)
1928 fn expr_call_lang_item_fn(
1931 lang_item: hir::LangItem,
1932 args: &'hir [hir::Expr<'hir>],
1933 ) -> &'hir hir::Expr<'hir> {
1934 self.arena.alloc(self.expr_call_lang_item_fn_mut(span, lang_item, args))
1937 fn expr_lang_item_path(
1940 lang_item: hir::LangItem,
1942 ) -> hir::Expr<'hir> {
1943 self.expr(span, hir::ExprKind::Path(hir::QPath::LangItem(lang_item, span)), attrs)
1946 pub(super) fn expr_ident(
1950 binding: hir::HirId,
1951 ) -> &'hir hir::Expr<'hir> {
1952 self.arena.alloc(self.expr_ident_mut(sp, ident, binding))
1955 pub(super) fn expr_ident_mut(
1959 binding: hir::HirId,
1960 ) -> hir::Expr<'hir> {
1961 self.expr_ident_with_attrs(sp, ident, binding, ThinVec::new())
1964 fn expr_ident_with_attrs(
1968 binding: hir::HirId,
1970 ) -> hir::Expr<'hir> {
1971 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
1973 self.arena.alloc(hir::Path {
1975 res: Res::Local(binding),
1976 segments: arena_vec![self; hir::PathSegment::from_ident(ident)],
1980 self.expr(span, expr_path, attrs)
1983 fn expr_unsafe(&mut self, expr: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
1984 let hir_id = self.next_id();
1985 let span = expr.span;
1988 hir::ExprKind::Block(
1989 self.arena.alloc(hir::Block {
1993 rules: hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::CompilerGenerated),
1995 targeted_by_break: false,
2003 fn expr_block_empty(&mut self, span: Span) -> &'hir hir::Expr<'hir> {
2004 let blk = self.block_all(span, &[], None);
2005 let expr = self.expr_block(blk, ThinVec::new());
2006 self.arena.alloc(expr)
2009 pub(super) fn expr_block(
2011 b: &'hir hir::Block<'hir>,
2013 ) -> hir::Expr<'hir> {
2014 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
2020 kind: hir::ExprKind<'hir>,
2022 ) -> hir::Expr<'hir> {
2023 hir::Expr { hir_id: self.next_id(), kind, span, attrs }
2026 fn field(&mut self, ident: Ident, expr: &'hir hir::Expr<'hir>, span: Span) -> hir::Field<'hir> {
2027 hir::Field { hir_id: self.next_id(), ident, span, expr, is_shorthand: false }
2030 fn arm(&mut self, pat: &'hir hir::Pat<'hir>, expr: &'hir hir::Expr<'hir>) -> hir::Arm<'hir> {
2032 hir_id: self.next_id(),