1 use super::{LoweringContext, ParamMode, ParenthesizedGenericArgs, ImplTraitContext};
2 use crate::hir::{self, HirVec};
3 use crate::hir::def::Res;
4 use crate::hir::ptr::P;
6 use rustc_data_structures::thin_vec::ThinVec;
9 use syntax::ptr::P as AstP;
11 use syntax::source_map::{respan, DesugaringKind, Span, Spanned};
12 use syntax::symbol::{sym, Symbol};
14 impl LoweringContext<'_> {
15 fn lower_exprs(&mut self, exprs: &[AstP<Expr>]) -> HirVec<hir::Expr> {
16 exprs.iter().map(|x| self.lower_expr(x)).collect()
19 pub(super) fn lower_expr(&mut self, e: &Expr) -> hir::Expr {
20 let kind = match e.node {
21 ExprKind::Box(ref inner) => hir::ExprKind::Box(P(self.lower_expr(inner))),
22 ExprKind::Array(ref exprs) => hir::ExprKind::Array(self.lower_exprs(exprs)),
23 ExprKind::Repeat(ref expr, ref count) => {
24 let expr = P(self.lower_expr(expr));
25 let count = self.lower_anon_const(count);
26 hir::ExprKind::Repeat(expr, count)
28 ExprKind::Tup(ref elts) => hir::ExprKind::Tup(self.lower_exprs(elts)),
29 ExprKind::Call(ref f, ref args) => {
30 let f = P(self.lower_expr(f));
31 hir::ExprKind::Call(f, self.lower_exprs(args))
33 ExprKind::MethodCall(ref seg, ref args) => {
34 let hir_seg = P(self.lower_path_segment(
39 ParenthesizedGenericArgs::Err,
40 ImplTraitContext::disallowed(),
43 let args = self.lower_exprs(args);
44 hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args)
46 ExprKind::Binary(binop, ref lhs, ref rhs) => {
47 let binop = self.lower_binop(binop);
48 let lhs = P(self.lower_expr(lhs));
49 let rhs = P(self.lower_expr(rhs));
50 hir::ExprKind::Binary(binop, lhs, rhs)
52 ExprKind::Unary(op, ref ohs) => {
53 let op = self.lower_unop(op);
54 let ohs = P(self.lower_expr(ohs));
55 hir::ExprKind::Unary(op, ohs)
57 ExprKind::Lit(ref l) => hir::ExprKind::Lit(respan(l.span, l.node.clone())),
58 ExprKind::Cast(ref expr, ref ty) => {
59 let expr = P(self.lower_expr(expr));
60 hir::ExprKind::Cast(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
62 ExprKind::Type(ref expr, ref ty) => {
63 let expr = P(self.lower_expr(expr));
64 hir::ExprKind::Type(expr, self.lower_ty(ty, ImplTraitContext::disallowed()))
66 ExprKind::AddrOf(m, ref ohs) => {
67 let m = self.lower_mutability(m);
68 let ohs = P(self.lower_expr(ohs));
69 hir::ExprKind::AddrOf(m, ohs)
71 ExprKind::Let(ref pat, ref scrutinee) => self.lower_expr_let(e.span, pat, scrutinee),
72 ExprKind::If(ref cond, ref then, ref else_opt) => {
73 self.lower_expr_if(e.span, cond, then, else_opt.as_deref())
75 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
76 this.lower_expr_while_in_loop_scope(e.span, cond, body, opt_label)
78 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
80 this.lower_block(body, false),
81 this.lower_label(opt_label),
82 hir::LoopSource::Loop,
85 ExprKind::TryBlock(ref body) => self.lower_expr_try_block(body),
86 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
87 P(self.lower_expr(expr)),
88 arms.iter().map(|x| self.lower_arm(x)).collect(),
89 hir::MatchSource::Normal,
91 ExprKind::Async(capture_clause, closure_node_id, ref block) => {
92 self.make_async_expr(capture_clause, closure_node_id, None, block.span, |this| {
93 this.with_new_scopes(|this| this.lower_block_expr(block))
96 ExprKind::Await(ref expr) => self.lower_expr_await(e.span, expr),
98 capture_clause, asyncness, movability, ref decl, ref body, fn_decl_span
99 ) => if let IsAsync::Async { closure_id, .. } = asyncness {
100 self.lower_expr_async_closure(capture_clause, closure_id, decl, body, fn_decl_span)
102 self.lower_expr_closure(capture_clause, movability, decl, body, fn_decl_span)
104 ExprKind::Block(ref blk, opt_label) => {
105 hir::ExprKind::Block(self.lower_block(blk,
106 opt_label.is_some()),
107 self.lower_label(opt_label))
109 ExprKind::Assign(ref el, ref er) => {
110 hir::ExprKind::Assign(P(self.lower_expr(el)), P(self.lower_expr(er)))
112 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
113 self.lower_binop(op),
114 P(self.lower_expr(el)),
115 P(self.lower_expr(er)),
117 ExprKind::Field(ref el, ident) => hir::ExprKind::Field(P(self.lower_expr(el)), ident),
118 ExprKind::Index(ref el, ref er) => {
119 hir::ExprKind::Index(P(self.lower_expr(el)), P(self.lower_expr(er)))
121 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
122 self.lower_expr_range_closed(e.span, e1, e2)
124 ExprKind::Range(ref e1, ref e2, lims) => {
125 self.lower_expr_range(e.span, e1.as_deref(), e2.as_deref(), lims)
127 ExprKind::Path(ref qself, ref path) => {
128 let qpath = self.lower_qpath(
133 ImplTraitContext::disallowed(),
135 hir::ExprKind::Path(qpath)
137 ExprKind::Break(opt_label, ref opt_expr) => {
138 hir::ExprKind::Break(
139 self.lower_jump_destination(e.id, opt_label),
140 opt_expr.as_ref().map(|x| P(self.lower_expr(x))),
143 ExprKind::Continue(opt_label) => {
144 hir::ExprKind::Continue(self.lower_jump_destination(e.id, opt_label))
146 ExprKind::Ret(ref e) => hir::ExprKind::Ret(e.as_ref().map(|x| P(self.lower_expr(x)))),
147 ExprKind::InlineAsm(ref asm) => self.lower_expr_asm(asm),
148 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => hir::ExprKind::Struct(
154 ImplTraitContext::disallowed(),
156 fields.iter().map(|x| self.lower_field(x)).collect(),
157 maybe_expr.as_ref().map(|x| P(self.lower_expr(x))),
159 ExprKind::Paren(ref ex) => {
160 let mut ex = self.lower_expr(ex);
161 // Include parens in span, but only if it is a super-span.
162 if e.span.contains(ex.span) {
165 // Merge attributes into the inner expression.
166 let mut attrs = e.attrs.clone();
167 attrs.extend::<Vec<_>>(ex.attrs.into());
172 ExprKind::Yield(ref opt_expr) => self.lower_expr_yield(e.span, opt_expr.as_deref()),
174 ExprKind::Err => hir::ExprKind::Err,
176 // Desugar `ExprForLoop`
177 // from: `[opt_ident]: for <pat> in <head> <body>`
178 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
179 return self.lower_expr_for(e, pat, head, body, opt_label);
181 ExprKind::Try(ref sub_expr) => self.lower_expr_try(e.span, sub_expr),
182 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
186 hir_id: self.lower_node_id(e.id),
189 attrs: e.attrs.clone(),
193 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
195 UnOp::Deref => hir::UnDeref,
196 UnOp::Not => hir::UnNot,
197 UnOp::Neg => hir::UnNeg,
201 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
204 BinOpKind::Add => hir::BinOpKind::Add,
205 BinOpKind::Sub => hir::BinOpKind::Sub,
206 BinOpKind::Mul => hir::BinOpKind::Mul,
207 BinOpKind::Div => hir::BinOpKind::Div,
208 BinOpKind::Rem => hir::BinOpKind::Rem,
209 BinOpKind::And => hir::BinOpKind::And,
210 BinOpKind::Or => hir::BinOpKind::Or,
211 BinOpKind::BitXor => hir::BinOpKind::BitXor,
212 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
213 BinOpKind::BitOr => hir::BinOpKind::BitOr,
214 BinOpKind::Shl => hir::BinOpKind::Shl,
215 BinOpKind::Shr => hir::BinOpKind::Shr,
216 BinOpKind::Eq => hir::BinOpKind::Eq,
217 BinOpKind::Lt => hir::BinOpKind::Lt,
218 BinOpKind::Le => hir::BinOpKind::Le,
219 BinOpKind::Ne => hir::BinOpKind::Ne,
220 BinOpKind::Ge => hir::BinOpKind::Ge,
221 BinOpKind::Gt => hir::BinOpKind::Gt,
227 /// Emit an error and lower `ast::ExprKind::Let(pat, scrutinee)` into:
229 /// match scrutinee { pats => true, _ => false }
231 fn lower_expr_let(&mut self, span: Span, pat: &Pat, scrutinee: &Expr) -> hir::ExprKind {
232 // If we got here, the `let` expression is not allowed.
234 .struct_span_err(span, "`let` expressions are not supported here")
235 .note("only supported directly in conditions of `if`- and `while`-expressions")
236 .note("as well as when nested within `&&` and parenthesis in those conditions")
239 // For better recovery, we emit:
241 // match scrutinee { pat => true, _ => false }
243 // While this doesn't fully match the user's intent, it has key advantages:
244 // 1. We can avoid using `abort_if_errors`.
245 // 2. We can typeck both `pat` and `scrutinee`.
246 // 3. `pat` is allowed to be refutable.
247 // 4. The return type of the block is `bool` which seems like what the user wanted.
248 let scrutinee = self.lower_expr(scrutinee);
250 let pat = self.lower_pat_top_hack(pat);
251 let expr = self.expr_bool(span, true);
252 self.arm(pat, P(expr))
255 let pat = self.pat_wild(span);
256 let expr = self.expr_bool(span, false);
257 self.arm(hir_vec![pat], P(expr))
259 hir::ExprKind::Match(
261 vec![then_arm, else_arm].into(),
262 hir::MatchSource::Normal,
271 else_opt: Option<&Expr>,
273 // FIXME(#53667): handle lowering of && and parens.
275 // `_ => else_block` where `else_block` is `{}` if there's `None`:
276 let else_pat = self.pat_wild(span);
277 let (else_expr, contains_else_clause) = match else_opt {
278 None => (self.expr_block_empty(span), false),
279 Some(els) => (self.lower_expr(els), true),
281 let else_arm = self.arm(hir_vec![else_pat], P(else_expr));
283 // Handle then + scrutinee:
284 let then_expr = self.lower_block_expr(then);
285 let (then_pat, scrutinee, desugar) = match cond.node {
286 // `<pat> => <then>`:
287 ExprKind::Let(ref pat, ref scrutinee) => {
288 let scrutinee = self.lower_expr(scrutinee);
289 let pat = self.lower_pat_top_hack(pat);
290 (pat, scrutinee, hir::MatchSource::IfLetDesugar { contains_else_clause })
295 let cond = self.lower_expr(cond);
296 let span_block = self.mark_span_with_reason(
297 DesugaringKind::CondTemporary,
301 // Wrap in a construct equivalent to `{ let _t = $cond; _t }`
302 // to preserve drop semantics since `if cond { ... }` does not
303 // let temporaries live outside of `cond`.
304 let cond = self.expr_drop_temps(span_block, P(cond), ThinVec::new());
305 let pat = self.pat_bool(span, true);
306 (hir_vec![pat], cond, hir::MatchSource::IfDesugar { contains_else_clause })
309 let then_arm = self.arm(then_pat, P(then_expr));
311 hir::ExprKind::Match(P(scrutinee), vec![then_arm, else_arm].into(), desugar)
314 fn lower_expr_while_in_loop_scope(
319 opt_label: Option<Label>
321 // FIXME(#53667): handle lowering of && and parens.
323 // Note that the block AND the condition are evaluated in the loop scope.
324 // This is done to allow `break` from inside the condition of the loop.
328 let else_pat = self.pat_wild(span);
329 let else_expr = self.expr_break(span, ThinVec::new());
330 self.arm(hir_vec![else_pat], else_expr)
333 // Handle then + scrutinee:
334 let then_expr = self.lower_block_expr(body);
335 let (then_pat, scrutinee, desugar, source) = match cond.node {
336 ExprKind::Let(ref pat, ref scrutinee) => {
339 // [opt_ident]: loop {
340 // match <sub_expr> {
345 let scrutinee = self.with_loop_condition_scope(|t| t.lower_expr(scrutinee));
346 let pat = self.lower_pat_top_hack(pat);
347 (pat, scrutinee, hir::MatchSource::WhileLetDesugar, hir::LoopSource::WhileLet)
350 // We desugar: `'label: while $cond $body` into:
354 // match drop-temps { $cond } {
362 let cond = self.with_loop_condition_scope(|this| this.lower_expr(cond));
363 let span_block = self.mark_span_with_reason(
364 DesugaringKind::CondTemporary,
368 // Wrap in a construct equivalent to `{ let _t = $cond; _t }`
369 // to preserve drop semantics since `while cond { ... }` does not
370 // let temporaries live outside of `cond`.
371 let cond = self.expr_drop_temps(span_block, P(cond), ThinVec::new());
373 let pat = self.pat_bool(span, true);
374 (hir_vec![pat], cond, hir::MatchSource::WhileDesugar, hir::LoopSource::While)
377 let then_arm = self.arm(then_pat, P(then_expr));
379 // `match <scrutinee> { ... }`
380 let match_expr = self.expr_match(
383 hir_vec![then_arm, else_arm],
387 // `[opt_ident]: loop { ... }`
389 P(self.block_expr(P(match_expr))),
390 self.lower_label(opt_label),
395 fn lower_expr_try_block(&mut self, body: &Block) -> hir::ExprKind {
396 self.with_catch_scope(body.id, |this| {
397 let unstable_span = this.mark_span_with_reason(
398 DesugaringKind::TryBlock,
400 this.allow_try_trait.clone(),
402 let mut block = this.lower_block(body, true).into_inner();
403 let tail = block.expr.take().map_or_else(
404 || this.expr_unit(this.sess.source_map().end_point(unstable_span)),
405 |x: P<hir::Expr>| x.into_inner(),
407 block.expr = Some(this.wrap_in_try_constructor(sym::from_ok, tail, unstable_span));
408 hir::ExprKind::Block(P(block), None)
412 fn wrap_in_try_constructor(
418 let path = &[sym::ops, sym::Try, method];
419 let from_err = P(self.expr_std_path(unstable_span, path, None, ThinVec::new()));
420 P(self.expr_call(e.span, from_err, hir_vec![e]))
423 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm {
425 hir_id: self.next_id(),
426 attrs: self.lower_attrs(&arm.attrs),
427 pats: self.lower_pat_top_hack(&arm.pat),
428 guard: match arm.guard {
429 Some(ref x) => Some(hir::Guard::If(P(self.lower_expr(x)))),
432 body: P(self.lower_expr(&arm.body)),
437 /// HACK(or_patterns; Centril | dlrobertson): For now we don't push down top level or-patterns
438 /// `p | q` into `hir::PatKind::Or(...)` as post-lowering bits of the compiler are not ready
439 /// to deal with it. This should by fixed by pushing it down to HIR and then HAIR.
440 fn lower_pat_top_hack(&mut self, pat: &Pat) -> HirVec<P<hir::Pat>> {
442 PatKind::Or(ref ps) => ps.iter().map(|x| self.lower_pat(x)).collect(),
443 _ => hir_vec![self.lower_pat(pat)],
447 pub(super) fn make_async_expr(
449 capture_clause: CaptureBy,
450 closure_node_id: NodeId,
451 ret_ty: Option<AstP<Ty>>,
453 body: impl FnOnce(&mut LoweringContext<'_>) -> hir::Expr,
455 let capture_clause = self.lower_capture_clause(capture_clause);
456 let output = match ret_ty {
457 Some(ty) => FunctionRetTy::Ty(ty),
458 None => FunctionRetTy::Default(span),
460 let ast_decl = FnDecl {
465 let decl = self.lower_fn_decl(&ast_decl, None, /* impl trait allowed */ false, None);
466 let body_id = self.lower_fn_body(&ast_decl, |this| {
467 this.generator_kind = Some(hir::GeneratorKind::Async);
471 // `static || -> <ret_ty> { body }`:
472 let generator_node = hir::ExprKind::Closure(
477 Some(hir::GeneratorMovability::Static)
479 let generator = hir::Expr {
480 hir_id: self.lower_node_id(closure_node_id),
481 node: generator_node,
483 attrs: ThinVec::new(),
486 // `future::from_generator`:
487 let unstable_span = self.mark_span_with_reason(
488 DesugaringKind::Async,
490 self.allow_gen_future.clone(),
492 let gen_future = self.expr_std_path(
494 &[sym::future, sym::from_generator],
499 // `future::from_generator(generator)`:
500 hir::ExprKind::Call(P(gen_future), hir_vec![generator])
503 /// Desugar `<expr>.await` into:
506 /// mut pinned => loop {
507 /// match ::std::future::poll_with_tls_context(unsafe {
508 /// <::std::pin::Pin>::new_unchecked(&mut pinned)
510 /// ::std::task::Poll::Ready(result) => break result,
511 /// ::std::task::Poll::Pending => {}
517 fn lower_expr_await(&mut self, await_span: Span, expr: &Expr) -> hir::ExprKind {
518 match self.generator_kind {
519 Some(hir::GeneratorKind::Async) => {},
520 Some(hir::GeneratorKind::Gen) |
522 let mut err = struct_span_err!(
526 "`await` is only allowed inside `async` functions and blocks"
528 err.span_label(await_span, "only allowed inside `async` functions and blocks");
529 if let Some(item_sp) = self.current_item {
530 err.span_label(item_sp, "this is not `async`");
535 let span = self.mark_span_with_reason(
536 DesugaringKind::Await,
540 let gen_future_span = self.mark_span_with_reason(
541 DesugaringKind::Await,
543 self.allow_gen_future.clone(),
546 let pinned_ident = Ident::with_dummy_span(sym::pinned);
547 let (pinned_pat, pinned_pat_hid) = self.pat_ident_binding_mode(
550 hir::BindingAnnotation::Mutable,
553 // ::std::future::poll_with_tls_context(unsafe {
554 // ::std::pin::Pin::new_unchecked(&mut pinned)
557 let pinned = P(self.expr_ident(span, pinned_ident, pinned_pat_hid));
558 let ref_mut_pinned = self.expr_mut_addr_of(span, pinned);
559 let pin_ty_id = self.next_id();
560 let new_unchecked_expr_kind = self.expr_call_std_assoc_fn(
563 &[sym::pin, sym::Pin],
565 hir_vec![ref_mut_pinned],
567 let new_unchecked = P(self.expr(span, new_unchecked_expr_kind, ThinVec::new()));
568 let unsafe_expr = self.expr_unsafe(new_unchecked);
569 P(self.expr_call_std_path(
571 &[sym::future, sym::poll_with_tls_context],
572 hir_vec![unsafe_expr],
576 // `::std::task::Poll::Ready(result) => break result`
577 let loop_node_id = self.sess.next_node_id();
578 let loop_hir_id = self.lower_node_id(loop_node_id);
580 let x_ident = Ident::with_dummy_span(sym::result);
581 let (x_pat, x_pat_hid) = self.pat_ident(span, x_ident);
582 let x_expr = P(self.expr_ident(span, x_ident, x_pat_hid));
583 let ready_pat = self.pat_std_enum(
585 &[sym::task, sym::Poll, sym::Ready],
588 let break_x = self.with_loop_scope(loop_node_id, |this| {
589 let expr_break = hir::ExprKind::Break(
590 this.lower_loop_destination(None),
593 P(this.expr(await_span, expr_break, ThinVec::new()))
595 self.arm(hir_vec![ready_pat], break_x)
598 // `::std::task::Poll::Pending => {}`
600 let pending_pat = self.pat_std_enum(
602 &[sym::task, sym::Poll, sym::Pending],
605 let empty_block = P(self.expr_block_empty(span));
606 self.arm(hir_vec![pending_pat], empty_block)
609 let inner_match_stmt = {
610 let match_expr = self.expr_match(
613 hir_vec![ready_arm, pending_arm],
614 hir::MatchSource::AwaitDesugar,
616 self.stmt_expr(span, match_expr)
620 let unit = self.expr_unit(span);
621 let yield_expr = self.expr(
623 hir::ExprKind::Yield(P(unit), hir::YieldSource::Await),
626 self.stmt_expr(span, yield_expr)
629 let loop_block = P(self.block_all(
631 hir_vec![inner_match_stmt, yield_stmt],
636 let loop_expr = P(hir::Expr {
638 node: hir::ExprKind::Loop(
641 hir::LoopSource::Loop,
644 attrs: ThinVec::new(),
647 // mut pinned => loop { ... }
648 let pinned_arm = self.arm(hir_vec![pinned_pat], loop_expr);
651 // mut pinned => loop { .. }
653 let expr = P(self.lower_expr(expr));
654 hir::ExprKind::Match(expr, hir_vec![pinned_arm], hir::MatchSource::AwaitDesugar)
657 fn lower_expr_closure(
659 capture_clause: CaptureBy,
660 movability: Movability,
665 // Lower outside new scope to preserve `is_in_loop_condition`.
666 let fn_decl = self.lower_fn_decl(decl, None, false, None);
668 self.with_new_scopes(|this| {
669 let prev = this.current_item;
670 this.current_item = Some(fn_decl_span);
671 let mut generator_kind = None;
672 let body_id = this.lower_fn_body(decl, |this| {
673 let e = this.lower_expr(body);
674 generator_kind = this.generator_kind;
677 let generator_option = this.generator_movability_for_fn(
683 let capture_clause = this.lower_capture_clause(capture_clause);
684 this.current_item = prev;
685 hir::ExprKind::Closure(
695 fn lower_capture_clause(&mut self, c: CaptureBy) -> hir::CaptureClause {
697 CaptureBy::Value => hir::CaptureByValue,
698 CaptureBy::Ref => hir::CaptureByRef,
702 fn generator_movability_for_fn(
706 generator_kind: Option<hir::GeneratorKind>,
707 movability: Movability,
708 ) -> Option<hir::GeneratorMovability> {
709 match generator_kind {
710 Some(hir::GeneratorKind::Gen) => {
711 if !decl.inputs.is_empty() {
716 "generators cannot have explicit parameters"
718 self.sess.abort_if_errors();
720 Some(match movability {
721 Movability::Movable => hir::GeneratorMovability::Movable,
722 Movability::Static => hir::GeneratorMovability::Static,
725 Some(hir::GeneratorKind::Async) => {
726 bug!("non-`async` closure body turned `async` during lowering");
729 if movability == Movability::Static {
734 "closures cannot be static"
742 fn lower_expr_async_closure(
744 capture_clause: CaptureBy,
750 let outer_decl = FnDecl {
751 inputs: decl.inputs.clone(),
752 output: FunctionRetTy::Default(fn_decl_span),
755 // We need to lower the declaration outside the new scope, because we
756 // have to conserve the state of being inside a loop condition for the
757 // closure argument types.
758 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
760 self.with_new_scopes(|this| {
761 // FIXME(cramertj): allow `async` non-`move` closures with arguments.
762 if capture_clause == CaptureBy::Ref && !decl.inputs.is_empty() {
767 "`async` non-`move` closures with parameters are not currently supported",
770 "consider using `let` statements to manually capture \
771 variables by reference before entering an `async move` closure"
776 // Transform `async |x: u8| -> X { ... }` into
777 // `|x: u8| future_from_generator(|| -> X { ... })`.
778 let body_id = this.lower_fn_body(&outer_decl, |this| {
779 let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output {
784 let async_body = this.make_async_expr(
785 capture_clause, closure_id, async_ret_ty, body.span,
787 this.with_new_scopes(|this| this.lower_expr(body))
790 this.expr(fn_decl_span, async_body, ThinVec::new())
792 hir::ExprKind::Closure(
793 this.lower_capture_clause(capture_clause),
802 /// Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`.
803 fn lower_expr_range_closed(&mut self, span: Span, e1: &Expr, e2: &Expr) -> hir::ExprKind {
804 let id = self.next_id();
805 let e1 = self.lower_expr(e1);
806 let e2 = self.lower_expr(e2);
807 self.expr_call_std_assoc_fn(
810 &[sym::ops, sym::RangeInclusive],
823 use syntax::ast::RangeLimits::*;
825 let path = match (e1, e2, lims) {
826 (None, None, HalfOpen) => sym::RangeFull,
827 (Some(..), None, HalfOpen) => sym::RangeFrom,
828 (None, Some(..), HalfOpen) => sym::RangeTo,
829 (Some(..), Some(..), HalfOpen) => sym::Range,
830 (None, Some(..), Closed) => sym::RangeToInclusive,
831 (Some(..), Some(..), Closed) => unreachable!(),
832 (_, None, Closed) => self.diagnostic()
833 .span_fatal(span, "inclusive range with no end")
837 let fields = e1.iter()
838 .map(|e| ("start", e))
839 .chain(e2.iter().map(|e| ("end", e)))
841 let expr = P(self.lower_expr(&e));
842 let ident = Ident::new(Symbol::intern(s), e.span);
843 self.field(ident, expr, e.span)
845 .collect::<P<[hir::Field]>>();
847 let is_unit = fields.is_empty();
848 let struct_path = [sym::ops, path];
849 let struct_path = self.std_path(span, &struct_path, None, is_unit);
850 let struct_path = hir::QPath::Resolved(None, P(struct_path));
853 hir::ExprKind::Path(struct_path)
855 hir::ExprKind::Struct(P(struct_path), fields, None)
859 fn lower_label(&mut self, label: Option<Label>) -> Option<hir::Label> {
860 label.map(|label| hir::Label {
865 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
866 let target_id = match destination {
868 if let Some(loop_id) = self.resolver.get_label_res(id) {
869 Ok(self.lower_node_id(loop_id))
871 Err(hir::LoopIdError::UnresolvedLabel)
878 .map(|id| Ok(self.lower_node_id(id)))
879 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
884 label: self.lower_label(destination.map(|(_, label)| label)),
889 fn lower_jump_destination(&mut self, id: NodeId, opt_label: Option<Label>) -> hir::Destination {
890 if self.is_in_loop_condition && opt_label.is_none() {
893 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
896 self.lower_loop_destination(opt_label.map(|label| (id, label)))
900 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
902 F: FnOnce(&mut LoweringContext<'_>) -> T,
904 let len = self.catch_scopes.len();
905 self.catch_scopes.push(catch_id);
907 let result = f(self);
910 self.catch_scopes.len(),
911 "catch scopes should be added and removed in stack order"
914 self.catch_scopes.pop().unwrap();
919 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
921 F: FnOnce(&mut LoweringContext<'_>) -> T,
923 // We're no longer in the base loop's condition; we're in another loop.
924 let was_in_loop_condition = self.is_in_loop_condition;
925 self.is_in_loop_condition = false;
927 let len = self.loop_scopes.len();
928 self.loop_scopes.push(loop_id);
930 let result = f(self);
933 self.loop_scopes.len(),
934 "loop scopes should be added and removed in stack order"
937 self.loop_scopes.pop().unwrap();
939 self.is_in_loop_condition = was_in_loop_condition;
944 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
946 F: FnOnce(&mut LoweringContext<'_>) -> T,
948 let was_in_loop_condition = self.is_in_loop_condition;
949 self.is_in_loop_condition = true;
951 let result = f(self);
953 self.is_in_loop_condition = was_in_loop_condition;
958 fn lower_expr_asm(&mut self, asm: &InlineAsm) -> hir::ExprKind {
959 let hir_asm = hir::InlineAsm {
960 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
963 .map(|out| hir::InlineAsmOutput {
964 constraint: out.constraint.clone(),
966 is_indirect: out.is_indirect,
970 asm: asm.asm.clone(),
971 asm_str_style: asm.asm_str_style,
972 clobbers: asm.clobbers.clone().into(),
973 volatile: asm.volatile,
974 alignstack: asm.alignstack,
975 dialect: asm.dialect,
978 let outputs = asm.outputs
980 .map(|out| self.lower_expr(&out.expr))
983 let inputs = asm.inputs
985 .map(|&(_, ref input)| self.lower_expr(input))
988 hir::ExprKind::InlineAsm(P(hir_asm), outputs, inputs)
991 fn lower_field(&mut self, f: &Field) -> hir::Field {
993 hir_id: self.next_id(),
995 expr: P(self.lower_expr(&f.expr)),
997 is_shorthand: f.is_shorthand,
1001 fn lower_expr_yield(&mut self, span: Span, opt_expr: Option<&Expr>) -> hir::ExprKind {
1002 match self.generator_kind {
1003 Some(hir::GeneratorKind::Gen) => {},
1004 Some(hir::GeneratorKind::Async) => {
1009 "`async` generators are not yet supported",
1011 self.sess.abort_if_errors();
1013 None => self.generator_kind = Some(hir::GeneratorKind::Gen),
1018 .map(|x| self.lower_expr(x))
1019 .unwrap_or_else(|| self.expr_unit(span));
1021 hir::ExprKind::Yield(P(expr), hir::YieldSource::Yield)
1024 /// Desugar `ExprForLoop` from: `[opt_ident]: for <pat> in <head> <body>` into:
1027 /// let result = match ::std::iter::IntoIterator::into_iter(<head>) {
1029 /// [opt_ident]: loop {
1031 /// match ::std::iter::Iterator::next(&mut iter) {
1032 /// ::std::option::Option::Some(val) => __next = val,
1033 /// ::std::option::Option::None => break
1035 /// let <pat> = __next;
1036 /// StmtKind::Expr(<body>);
1049 opt_label: Option<Label>,
1052 let mut head = self.lower_expr(head);
1053 let head_sp = head.span;
1054 let desugared_span = self.mark_span_with_reason(
1055 DesugaringKind::ForLoop,
1059 head.span = desugared_span;
1061 let iter = Ident::with_dummy_span(sym::iter);
1063 let next_ident = Ident::with_dummy_span(sym::__next);
1064 let (next_pat, next_pat_hid) = self.pat_ident_binding_mode(
1067 hir::BindingAnnotation::Mutable,
1070 // `::std::option::Option::Some(val) => __next = val`
1072 let val_ident = Ident::with_dummy_span(sym::val);
1073 let (val_pat, val_pat_hid) = self.pat_ident(pat.span, val_ident);
1074 let val_expr = P(self.expr_ident(pat.span, val_ident, val_pat_hid));
1075 let next_expr = P(self.expr_ident(pat.span, next_ident, next_pat_hid));
1076 let assign = P(self.expr(
1078 hir::ExprKind::Assign(next_expr, val_expr),
1081 let some_pat = self.pat_some(pat.span, val_pat);
1082 self.arm(hir_vec![some_pat], assign)
1085 // `::std::option::Option::None => break`
1088 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
1089 let pat = self.pat_none(e.span);
1090 self.arm(hir_vec![pat], break_expr)
1094 let (iter_pat, iter_pat_nid) = self.pat_ident_binding_mode(
1097 hir::BindingAnnotation::Mutable
1100 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
1102 let iter = P(self.expr_ident(head_sp, iter, iter_pat_nid));
1103 let ref_mut_iter = self.expr_mut_addr_of(head_sp, iter);
1104 let next_path = &[sym::iter, sym::Iterator, sym::next];
1105 let next_expr = P(self.expr_call_std_path(
1108 hir_vec![ref_mut_iter],
1110 let arms = hir_vec![pat_arm, break_arm];
1112 self.expr_match(head_sp, next_expr, arms, hir::MatchSource::ForLoopDesugar)
1114 let match_stmt = self.stmt_expr(head_sp, match_expr);
1116 let next_expr = P(self.expr_ident(head_sp, next_ident, next_pat_hid));
1119 let next_let = self.stmt_let_pat(
1124 hir::LocalSource::ForLoopDesugar,
1127 // `let <pat> = __next`
1128 let pat = self.lower_pat(pat);
1129 let pat_let = self.stmt_let_pat(
1134 hir::LocalSource::ForLoopDesugar,
1137 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
1138 let body_expr = self.expr_block(body_block, ThinVec::new());
1139 let body_stmt = self.stmt_expr(body.span, body_expr);
1141 let loop_block = P(self.block_all(
1143 hir_vec![next_let, match_stmt, pat_let, body_stmt],
1147 // `[opt_ident]: loop { ... }`
1148 let loop_expr = hir::ExprKind::Loop(
1150 self.lower_label(opt_label),
1151 hir::LoopSource::ForLoop,
1153 let loop_expr = P(hir::Expr {
1154 hir_id: self.lower_node_id(e.id),
1157 attrs: ThinVec::new(),
1160 // `mut iter => { ... }`
1161 let iter_arm = self.arm(hir_vec![iter_pat], loop_expr);
1163 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
1164 let into_iter_expr = {
1165 let into_iter_path =
1166 &[sym::iter, sym::IntoIterator, sym::into_iter];
1167 P(self.expr_call_std_path(
1174 let match_expr = P(self.expr_match(
1178 hir::MatchSource::ForLoopDesugar,
1181 // This is effectively `{ let _result = ...; _result }`.
1182 // The construct was introduced in #21984 and is necessary to make sure that
1183 // temporaries in the `head` expression are dropped and do not leak to the
1184 // surrounding scope of the `match` since the `match` is not a terminating scope.
1186 // Also, add the attributes to the outer returned expr node.
1187 self.expr_drop_temps(head_sp, match_expr, e.attrs.clone())
1190 /// Desugar `ExprKind::Try` from: `<expr>?` into:
1192 /// match Try::into_result(<expr>) {
1193 /// Ok(val) => #[allow(unreachable_code)] val,
1194 /// Err(err) => #[allow(unreachable_code)]
1195 /// // If there is an enclosing `try {...}`:
1196 /// break 'catch_target Try::from_error(From::from(err)),
1198 /// return Try::from_error(From::from(err)),
1201 fn lower_expr_try(&mut self, span: Span, sub_expr: &Expr) -> hir::ExprKind {
1202 let unstable_span = self.mark_span_with_reason(
1203 DesugaringKind::QuestionMark,
1205 self.allow_try_trait.clone(),
1207 let try_span = self.sess.source_map().end_point(span);
1208 let try_span = self.mark_span_with_reason(
1209 DesugaringKind::QuestionMark,
1211 self.allow_try_trait.clone(),
1214 // `Try::into_result(<expr>)`
1217 let sub_expr = self.lower_expr(sub_expr);
1219 let path = &[sym::ops, sym::Try, sym::into_result];
1220 P(self.expr_call_std_path(unstable_span, path, hir_vec![sub_expr]))
1223 // `#[allow(unreachable_code)]`
1225 // `allow(unreachable_code)`
1227 let allow_ident = Ident::new(sym::allow, span);
1228 let uc_ident = Ident::new(sym::unreachable_code, span);
1229 let uc_nested = attr::mk_nested_word_item(uc_ident);
1230 attr::mk_list_item(allow_ident, vec![uc_nested])
1232 attr::mk_attr_outer(allow)
1234 let attrs = vec![attr];
1236 // `Ok(val) => #[allow(unreachable_code)] val,`
1238 let val_ident = Ident::with_dummy_span(sym::val);
1239 let (val_pat, val_pat_nid) = self.pat_ident(span, val_ident);
1240 let val_expr = P(self.expr_ident_with_attrs(
1244 ThinVec::from(attrs.clone()),
1246 let ok_pat = self.pat_ok(span, val_pat);
1247 self.arm(hir_vec![ok_pat], val_expr)
1250 // `Err(err) => #[allow(unreachable_code)]
1251 // return Try::from_error(From::from(err)),`
1253 let err_ident = Ident::with_dummy_span(sym::err);
1254 let (err_local, err_local_nid) = self.pat_ident(try_span, err_ident);
1256 let from_path = &[sym::convert, sym::From, sym::from];
1257 let err_expr = self.expr_ident(try_span, err_ident, err_local_nid);
1258 self.expr_call_std_path(try_span, from_path, hir_vec![err_expr])
1261 self.wrap_in_try_constructor(sym::from_error, from_expr, unstable_span);
1262 let thin_attrs = ThinVec::from(attrs);
1263 let catch_scope = self.catch_scopes.last().map(|x| *x);
1264 let ret_expr = if let Some(catch_node) = catch_scope {
1265 let target_id = Ok(self.lower_node_id(catch_node));
1268 hir::ExprKind::Break(
1273 Some(from_err_expr),
1278 P(self.expr(try_span, hir::ExprKind::Ret(Some(from_err_expr)), thin_attrs))
1281 let err_pat = self.pat_err(try_span, err_local);
1282 self.arm(hir_vec![err_pat], ret_expr)
1285 hir::ExprKind::Match(
1287 hir_vec![err_arm, ok_arm],
1288 hir::MatchSource::TryDesugar,
1292 // =========================================================================
1293 // Helper methods for building HIR.
1294 // =========================================================================
1296 /// Constructs a `true` or `false` literal expression.
1297 pub(super) fn expr_bool(&mut self, span: Span, val: bool) -> hir::Expr {
1298 let lit = Spanned { span, node: LitKind::Bool(val) };
1299 self.expr(span, hir::ExprKind::Lit(lit), ThinVec::new())
1302 /// Wrap the given `expr` in a terminating scope using `hir::ExprKind::DropTemps`.
1304 /// In terms of drop order, it has the same effect as wrapping `expr` in
1305 /// `{ let _t = $expr; _t }` but should provide better compile-time performance.
1307 /// The drop order can be important in e.g. `if expr { .. }`.
1308 pub(super) fn expr_drop_temps(
1312 attrs: ThinVec<Attribute>
1314 self.expr(span, hir::ExprKind::DropTemps(expr), attrs)
1321 arms: hir::HirVec<hir::Arm>,
1322 source: hir::MatchSource,
1324 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
1327 fn expr_break(&mut self, span: Span, attrs: ThinVec<Attribute>) -> P<hir::Expr> {
1328 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
1329 P(self.expr(span, expr_break, attrs))
1332 fn expr_mut_addr_of(&mut self, span: Span, e: P<hir::Expr>) -> hir::Expr {
1333 self.expr(span, hir::ExprKind::AddrOf(hir::MutMutable, e), ThinVec::new())
1336 fn expr_unit(&mut self, sp: Span) -> hir::Expr {
1337 self.expr_tuple(sp, hir_vec![])
1340 fn expr_tuple(&mut self, sp: Span, exprs: hir::HirVec<hir::Expr>) -> hir::Expr {
1341 self.expr(sp, hir::ExprKind::Tup(exprs), ThinVec::new())
1348 args: hir::HirVec<hir::Expr>,
1350 self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new())
1353 // Note: associated functions must use `expr_call_std_path`.
1354 fn expr_call_std_path(
1357 path_components: &[Symbol],
1358 args: hir::HirVec<hir::Expr>,
1360 let path = P(self.expr_std_path(span, path_components, None, ThinVec::new()));
1361 self.expr_call(span, path, args)
1364 // Create an expression calling an associated function of an std type.
1366 // Associated functions cannot be resolved through the normal `std_path` function,
1367 // as they are resolved differently and so cannot use `expr_call_std_path`.
1369 // This function accepts the path component (`ty_path_components`) separately from
1370 // the name of the associated function (`assoc_fn_name`) in order to facilitate
1371 // separate resolution of the type and creation of a path referring to its associated
1373 fn expr_call_std_assoc_fn(
1375 ty_path_id: hir::HirId,
1377 ty_path_components: &[Symbol],
1378 assoc_fn_name: &str,
1379 args: hir::HirVec<hir::Expr>,
1380 ) -> hir::ExprKind {
1381 let ty_path = P(self.std_path(span, ty_path_components, None, false));
1382 let ty = P(self.ty_path(ty_path_id, span, hir::QPath::Resolved(None, ty_path)));
1383 let fn_seg = P(hir::PathSegment::from_ident(Ident::from_str(assoc_fn_name)));
1384 let fn_path = hir::QPath::TypeRelative(ty, fn_seg);
1385 let fn_expr = P(self.expr(span, hir::ExprKind::Path(fn_path), ThinVec::new()));
1386 hir::ExprKind::Call(fn_expr, args)
1392 components: &[Symbol],
1393 params: Option<P<hir::GenericArgs>>,
1394 attrs: ThinVec<Attribute>,
1396 let path = self.std_path(span, components, params, true);
1399 hir::ExprKind::Path(hir::QPath::Resolved(None, P(path))),
1404 pub(super) fn expr_ident(&mut self, sp: Span, ident: Ident, binding: hir::HirId) -> hir::Expr {
1405 self.expr_ident_with_attrs(sp, ident, binding, ThinVec::new())
1408 fn expr_ident_with_attrs(
1412 binding: hir::HirId,
1413 attrs: ThinVec<Attribute>,
1415 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
1419 res: Res::Local(binding),
1420 segments: hir_vec![hir::PathSegment::from_ident(ident)],
1424 self.expr(span, expr_path, attrs)
1427 fn expr_unsafe(&mut self, expr: P<hir::Expr>) -> hir::Expr {
1428 let hir_id = self.next_id();
1429 let span = expr.span;
1432 hir::ExprKind::Block(P(hir::Block {
1436 rules: hir::UnsafeBlock(hir::CompilerGenerated),
1438 targeted_by_break: false,
1444 fn expr_block_empty(&mut self, span: Span) -> hir::Expr {
1445 let blk = self.block_all(span, hir_vec![], None);
1446 self.expr_block(P(blk), ThinVec::new())
1449 pub(super) fn expr_block(&mut self, b: P<hir::Block>, attrs: ThinVec<Attribute>) -> hir::Expr {
1450 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
1456 node: hir::ExprKind,
1457 attrs: ThinVec<Attribute>
1460 hir_id: self.next_id(),
1467 fn field(&mut self, ident: Ident, expr: P<hir::Expr>, span: Span) -> hir::Field {
1469 hir_id: self.next_id(),
1473 is_shorthand: false,
1477 /// HACK(or_patterns; Centril | dlrobertson): For now we don't push down top level or-patterns
1478 /// `p | q` into `hir::PatKind::Or(...)` as post-lowering bits of the compiler are not ready
1479 /// to deal with it. This should by fixed by pushing it down to HIR and then HAIR.
1480 fn arm(&mut self, pats: HirVec<P<hir::Pat>>, expr: P<hir::Expr>) -> hir::Arm {
1482 hir_id: self.next_id(),