1 use super::{ImplTraitContext, LoweringContext, ParamMode, ParenthesizedGenericArgs};
5 use rustc::hir::def::Res;
6 use rustc_data_structures::thin_vec::ThinVec;
7 use rustc_error_codes::*;
8 use rustc_span::source_map::{respan, DesugaringKind, Span, Spanned};
9 use rustc_span::symbol::{sym, Symbol};
12 use syntax::ptr::P as AstP;
13 use syntax::{span_err, struct_span_err};
15 impl<'hir> LoweringContext<'_, 'hir> {
16 fn lower_exprs(&mut self, exprs: &[AstP<Expr>]) -> &'hir [hir::Expr<'hir>] {
17 self.arena.alloc_from_iter(exprs.iter().map(|x| self.lower_expr_mut(x)))
20 pub(super) fn lower_expr(&mut self, e: &Expr) -> &'hir hir::Expr<'hir> {
21 self.arena.alloc(self.lower_expr_mut(e))
24 pub(super) fn lower_expr_mut(&mut self, e: &Expr) -> hir::Expr<'hir> {
25 let kind = match e.kind {
26 ExprKind::Box(ref inner) => hir::ExprKind::Box(self.lower_expr(inner)),
27 ExprKind::Array(ref exprs) => hir::ExprKind::Array(self.lower_exprs(exprs)),
28 ExprKind::Repeat(ref expr, ref count) => {
29 let expr = self.lower_expr(expr);
30 let count = self.lower_anon_const(count);
31 hir::ExprKind::Repeat(expr, count)
33 ExprKind::Tup(ref elts) => hir::ExprKind::Tup(self.lower_exprs(elts)),
34 ExprKind::Call(ref f, ref args) => {
35 let f = self.lower_expr(f);
36 hir::ExprKind::Call(f, self.lower_exprs(args))
38 ExprKind::MethodCall(ref seg, ref args) => {
39 let hir_seg = self.arena.alloc(self.lower_path_segment(
44 ParenthesizedGenericArgs::Err,
45 ImplTraitContext::disallowed(),
48 let args = self.lower_exprs(args);
49 hir::ExprKind::MethodCall(hir_seg, seg.ident.span, args)
51 ExprKind::Binary(binop, ref lhs, ref rhs) => {
52 let binop = self.lower_binop(binop);
53 let lhs = self.lower_expr(lhs);
54 let rhs = self.lower_expr(rhs);
55 hir::ExprKind::Binary(binop, lhs, rhs)
57 ExprKind::Unary(op, ref ohs) => {
58 let op = self.lower_unop(op);
59 let ohs = self.lower_expr(ohs);
60 hir::ExprKind::Unary(op, ohs)
62 ExprKind::Lit(ref l) => hir::ExprKind::Lit(respan(l.span, l.kind.clone())),
63 ExprKind::Cast(ref expr, ref ty) => {
64 let expr = self.lower_expr(expr);
65 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
66 hir::ExprKind::Cast(expr, ty)
68 ExprKind::Type(ref expr, ref ty) => {
69 let expr = self.lower_expr(expr);
70 let ty = self.lower_ty(ty, ImplTraitContext::disallowed());
71 hir::ExprKind::Type(expr, ty)
73 ExprKind::AddrOf(k, m, ref ohs) => {
74 let ohs = self.lower_expr(ohs);
75 hir::ExprKind::AddrOf(k, m, ohs)
77 ExprKind::Let(ref pat, ref scrutinee) => self.lower_expr_let(e.span, pat, scrutinee),
78 ExprKind::If(ref cond, ref then, ref else_opt) => {
79 self.lower_expr_if(e.span, cond, then, else_opt.as_deref())
81 ExprKind::While(ref cond, ref body, opt_label) => self.with_loop_scope(e.id, |this| {
82 this.lower_expr_while_in_loop_scope(e.span, cond, body, opt_label)
84 ExprKind::Loop(ref body, opt_label) => self.with_loop_scope(e.id, |this| {
85 hir::ExprKind::Loop(this.lower_block(body, false), opt_label, hir::LoopSource::Loop)
87 ExprKind::TryBlock(ref body) => self.lower_expr_try_block(body),
88 ExprKind::Match(ref expr, ref arms) => hir::ExprKind::Match(
89 self.lower_expr(expr),
90 self.arena.alloc_from_iter(arms.iter().map(|x| self.lower_arm(x))),
91 hir::MatchSource::Normal,
93 ExprKind::Async(capture_clause, closure_node_id, ref block) => self.make_async_expr(
98 hir::AsyncGeneratorKind::Block,
99 |this| this.with_new_scopes(|this| this.lower_block_expr(block)),
101 ExprKind::Await(ref expr) => self.lower_expr_await(e.span, expr),
110 if let IsAsync::Async { closure_id, .. } = asyncness {
111 self.lower_expr_async_closure(
119 self.lower_expr_closure(capture_clause, movability, decl, body, fn_decl_span)
122 ExprKind::Block(ref blk, opt_label) => {
123 hir::ExprKind::Block(self.lower_block(blk, opt_label.is_some()), opt_label)
125 ExprKind::Assign(ref el, ref er, span) => {
126 hir::ExprKind::Assign(self.lower_expr(el), self.lower_expr(er), span)
128 ExprKind::AssignOp(op, ref el, ref er) => hir::ExprKind::AssignOp(
129 self.lower_binop(op),
133 ExprKind::Field(ref el, ident) => hir::ExprKind::Field(self.lower_expr(el), ident),
134 ExprKind::Index(ref el, ref er) => {
135 hir::ExprKind::Index(self.lower_expr(el), self.lower_expr(er))
137 ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => {
138 self.lower_expr_range_closed(e.span, e1, e2)
140 ExprKind::Range(ref e1, ref e2, lims) => {
141 self.lower_expr_range(e.span, e1.as_deref(), e2.as_deref(), lims)
143 ExprKind::Path(ref qself, ref path) => {
144 let qpath = self.lower_qpath(
149 ImplTraitContext::disallowed(),
151 hir::ExprKind::Path(qpath)
153 ExprKind::Break(opt_label, ref opt_expr) => {
154 let opt_expr = opt_expr.as_ref().map(|x| self.lower_expr(x));
155 hir::ExprKind::Break(self.lower_jump_destination(e.id, opt_label), opt_expr)
157 ExprKind::Continue(opt_label) => {
158 hir::ExprKind::Continue(self.lower_jump_destination(e.id, opt_label))
160 ExprKind::Ret(ref e) => {
161 let e = e.as_ref().map(|x| self.lower_expr(x));
162 hir::ExprKind::Ret(e)
164 ExprKind::InlineAsm(ref asm) => self.lower_expr_asm(asm),
165 ExprKind::Struct(ref path, ref fields, ref maybe_expr) => {
166 let maybe_expr = maybe_expr.as_ref().map(|x| self.lower_expr(x));
167 hir::ExprKind::Struct(
168 self.arena.alloc(self.lower_qpath(
173 ImplTraitContext::disallowed(),
175 self.arena.alloc_from_iter(fields.iter().map(|x| self.lower_field(x))),
179 ExprKind::Paren(ref ex) => {
180 let mut ex = self.lower_expr_mut(ex);
181 // Include parens in span, but only if it is a super-span.
182 if e.span.contains(ex.span) {
185 // Merge attributes into the inner expression.
186 let mut attrs = e.attrs.clone();
187 attrs.extend::<Vec<_>>(ex.attrs.into());
192 ExprKind::Yield(ref opt_expr) => self.lower_expr_yield(e.span, opt_expr.as_deref()),
194 ExprKind::Err => hir::ExprKind::Err,
196 // Desugar `ExprForLoop`
197 // from: `[opt_ident]: for <pat> in <head> <body>`
198 ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => {
199 return self.lower_expr_for(e, pat, head, body, opt_label);
201 ExprKind::Try(ref sub_expr) => self.lower_expr_try(e.span, sub_expr),
202 ExprKind::Mac(_) => panic!("Shouldn't exist here"),
205 hir::Expr { hir_id: self.lower_node_id(e.id), kind, span: e.span, attrs: e.attrs.clone() }
208 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
210 UnOp::Deref => hir::UnDeref,
211 UnOp::Not => hir::UnNot,
212 UnOp::Neg => hir::UnNeg,
216 fn lower_binop(&mut self, b: BinOp) -> hir::BinOp {
219 BinOpKind::Add => hir::BinOpKind::Add,
220 BinOpKind::Sub => hir::BinOpKind::Sub,
221 BinOpKind::Mul => hir::BinOpKind::Mul,
222 BinOpKind::Div => hir::BinOpKind::Div,
223 BinOpKind::Rem => hir::BinOpKind::Rem,
224 BinOpKind::And => hir::BinOpKind::And,
225 BinOpKind::Or => hir::BinOpKind::Or,
226 BinOpKind::BitXor => hir::BinOpKind::BitXor,
227 BinOpKind::BitAnd => hir::BinOpKind::BitAnd,
228 BinOpKind::BitOr => hir::BinOpKind::BitOr,
229 BinOpKind::Shl => hir::BinOpKind::Shl,
230 BinOpKind::Shr => hir::BinOpKind::Shr,
231 BinOpKind::Eq => hir::BinOpKind::Eq,
232 BinOpKind::Lt => hir::BinOpKind::Lt,
233 BinOpKind::Le => hir::BinOpKind::Le,
234 BinOpKind::Ne => hir::BinOpKind::Ne,
235 BinOpKind::Ge => hir::BinOpKind::Ge,
236 BinOpKind::Gt => hir::BinOpKind::Gt,
242 /// Emit an error and lower `ast::ExprKind::Let(pat, scrutinee)` into:
244 /// match scrutinee { pats => true, _ => false }
246 fn lower_expr_let(&mut self, span: Span, pat: &Pat, scrutinee: &Expr) -> hir::ExprKind<'hir> {
247 // If we got here, the `let` expression is not allowed.
249 if self.sess.opts.unstable_features.is_nightly_build() {
251 .struct_span_err(span, "`let` expressions are not supported here")
252 .note("only supported directly in conditions of `if`- and `while`-expressions")
253 .note("as well as when nested within `&&` and parenthesis in those conditions")
257 .struct_span_err(span, "expected expression, found statement (`let`)")
258 .note("variable declaration using `let` is a statement")
262 // For better recovery, we emit:
264 // match scrutinee { pat => true, _ => false }
266 // While this doesn't fully match the user's intent, it has key advantages:
267 // 1. We can avoid using `abort_if_errors`.
268 // 2. We can typeck both `pat` and `scrutinee`.
269 // 3. `pat` is allowed to be refutable.
270 // 4. The return type of the block is `bool` which seems like what the user wanted.
271 let scrutinee = self.lower_expr(scrutinee);
273 let pat = self.lower_pat(pat);
274 let expr = self.expr_bool(span, true);
278 let pat = self.pat_wild(span);
279 let expr = self.expr_bool(span, false);
282 hir::ExprKind::Match(
284 arena_vec![self; then_arm, else_arm],
285 hir::MatchSource::Normal,
294 else_opt: Option<&Expr>,
295 ) -> hir::ExprKind<'hir> {
296 // FIXME(#53667): handle lowering of && and parens.
298 // `_ => else_block` where `else_block` is `{}` if there's `None`:
299 let else_pat = self.pat_wild(span);
300 let (else_expr, contains_else_clause) = match else_opt {
301 None => (self.expr_block_empty(span), false),
302 Some(els) => (self.lower_expr(els), true),
304 let else_arm = self.arm(else_pat, else_expr);
306 // Handle then + scrutinee:
307 let then_expr = self.lower_block_expr(then);
308 let (then_pat, scrutinee, desugar) = match cond.kind {
309 // `<pat> => <then>`:
310 ExprKind::Let(ref pat, ref scrutinee) => {
311 let scrutinee = self.lower_expr(scrutinee);
312 let pat = self.lower_pat(pat);
313 (pat, scrutinee, hir::MatchSource::IfLetDesugar { contains_else_clause })
318 let cond = self.lower_expr(cond);
320 self.mark_span_with_reason(DesugaringKind::CondTemporary, cond.span, None);
321 // Wrap in a construct equivalent to `{ let _t = $cond; _t }`
322 // to preserve drop semantics since `if cond { ... }` does not
323 // let temporaries live outside of `cond`.
324 let cond = self.expr_drop_temps(span_block, cond, ThinVec::new());
325 let pat = self.pat_bool(span, true);
326 (pat, cond, hir::MatchSource::IfDesugar { contains_else_clause })
329 let then_arm = self.arm(then_pat, self.arena.alloc(then_expr));
331 hir::ExprKind::Match(scrutinee, arena_vec![self; then_arm, else_arm], desugar)
334 fn lower_expr_while_in_loop_scope(
339 opt_label: Option<Label>,
340 ) -> hir::ExprKind<'hir> {
341 // FIXME(#53667): handle lowering of && and parens.
343 // Note that the block AND the condition are evaluated in the loop scope.
344 // This is done to allow `break` from inside the condition of the loop.
348 let else_pat = self.pat_wild(span);
349 let else_expr = self.expr_break(span, ThinVec::new());
350 self.arm(else_pat, else_expr)
353 // Handle then + scrutinee:
354 let then_expr = self.lower_block_expr(body);
355 let (then_pat, scrutinee, desugar, source) = match cond.kind {
356 ExprKind::Let(ref pat, ref scrutinee) => {
359 // [opt_ident]: loop {
360 // match <sub_expr> {
365 let scrutinee = self.with_loop_condition_scope(|t| t.lower_expr(scrutinee));
366 let pat = self.lower_pat(pat);
367 (pat, scrutinee, hir::MatchSource::WhileLetDesugar, hir::LoopSource::WhileLet)
370 // We desugar: `'label: while $cond $body` into:
374 // match drop-temps { $cond } {
382 let cond = self.with_loop_condition_scope(|this| this.lower_expr(cond));
384 self.mark_span_with_reason(DesugaringKind::CondTemporary, cond.span, None);
385 // Wrap in a construct equivalent to `{ let _t = $cond; _t }`
386 // to preserve drop semantics since `while cond { ... }` does not
387 // let temporaries live outside of `cond`.
388 let cond = self.expr_drop_temps(span_block, cond, ThinVec::new());
390 let pat = self.pat_bool(span, true);
391 (pat, cond, hir::MatchSource::WhileDesugar, hir::LoopSource::While)
394 let then_arm = self.arm(then_pat, self.arena.alloc(then_expr));
396 // `match <scrutinee> { ... }`
397 let match_expr = self.expr_match(
400 arena_vec![self; then_arm, else_arm],
404 // `[opt_ident]: loop { ... }`
405 hir::ExprKind::Loop(self.block_expr(self.arena.alloc(match_expr)), opt_label, source)
408 /// Desugar `try { <stmts>; <expr> }` into `{ <stmts>; ::std::ops::Try::from_ok(<expr>) }`,
409 /// `try { <stmts>; }` into `{ <stmts>; ::std::ops::Try::from_ok(()) }`
410 /// and save the block id to use it as a break target for desugaring of the `?` operator.
411 fn lower_expr_try_block(&mut self, body: &Block) -> hir::ExprKind<'hir> {
412 self.with_catch_scope(body.id, |this| {
413 let mut block = this.lower_block_noalloc(body, true);
415 let try_span = this.mark_span_with_reason(
416 DesugaringKind::TryBlock,
418 this.allow_try_trait.clone(),
421 // Final expression of the block (if present) or `()` with span at the end of block
422 let tail_expr = block
425 .unwrap_or_else(|| this.expr_unit(this.sess.source_map().end_point(try_span)));
427 let ok_wrapped_span =
428 this.mark_span_with_reason(DesugaringKind::TryBlock, tail_expr.span, None);
430 // `::std::ops::Try::from_ok($tail_expr)`
431 block.expr = Some(this.wrap_in_try_constructor(
438 hir::ExprKind::Block(this.arena.alloc(block), None)
442 fn wrap_in_try_constructor(
446 expr: &'hir hir::Expr<'hir>,
448 ) -> &'hir hir::Expr<'hir> {
449 let path = &[sym::ops, sym::Try, method];
451 self.arena.alloc(self.expr_std_path(method_span, path, None, ThinVec::new()));
452 self.expr_call(overall_span, constructor, std::slice::from_ref(expr))
455 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm<'hir> {
457 hir_id: self.next_id(),
458 attrs: self.lower_attrs(&arm.attrs),
459 pat: self.lower_pat(&arm.pat),
460 guard: match arm.guard {
461 Some(ref x) => Some(hir::Guard::If(self.lower_expr(x))),
464 body: self.lower_expr(&arm.body),
469 pub(super) fn make_async_expr(
471 capture_clause: CaptureBy,
472 closure_node_id: NodeId,
473 ret_ty: Option<AstP<Ty>>,
475 async_gen_kind: hir::AsyncGeneratorKind,
476 body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
477 ) -> hir::ExprKind<'hir> {
478 let output = match ret_ty {
479 Some(ty) => FunctionRetTy::Ty(ty),
480 None => FunctionRetTy::Default(span),
482 let ast_decl = FnDecl { inputs: vec![], output };
483 let decl = self.lower_fn_decl(&ast_decl, None, /* impl trait allowed */ false, None);
484 let body_id = self.lower_fn_body(&ast_decl, |this| {
485 this.generator_kind = Some(hir::GeneratorKind::Async(async_gen_kind));
489 // `static || -> <ret_ty> { body }`:
490 let generator_kind = hir::ExprKind::Closure(
495 Some(hir::Movability::Static),
497 let generator = hir::Expr {
498 hir_id: self.lower_node_id(closure_node_id),
499 kind: generator_kind,
501 attrs: ThinVec::new(),
504 // `future::from_generator`:
506 self.mark_span_with_reason(DesugaringKind::Async, span, self.allow_gen_future.clone());
507 let gen_future = self.expr_std_path(
509 &[sym::future, sym::from_generator],
514 // `future::from_generator(generator)`:
515 hir::ExprKind::Call(self.arena.alloc(gen_future), arena_vec![self; generator])
518 /// Desugar `<expr>.await` into:
521 /// mut pinned => loop {
522 /// match ::std::future::poll_with_tls_context(unsafe {
523 /// <::std::pin::Pin>::new_unchecked(&mut pinned)
525 /// ::std::task::Poll::Ready(result) => break result,
526 /// ::std::task::Poll::Pending => {}
532 fn lower_expr_await(&mut self, await_span: Span, expr: &Expr) -> hir::ExprKind<'hir> {
533 match self.generator_kind {
534 Some(hir::GeneratorKind::Async(_)) => {}
535 Some(hir::GeneratorKind::Gen) | None => {
536 let mut err = struct_span_err!(
540 "`await` is only allowed inside `async` functions and blocks"
542 err.span_label(await_span, "only allowed inside `async` functions and blocks");
543 if let Some(item_sp) = self.current_item {
544 err.span_label(item_sp, "this is not `async`");
549 let span = self.mark_span_with_reason(DesugaringKind::Await, await_span, None);
550 let gen_future_span = self.mark_span_with_reason(
551 DesugaringKind::Await,
553 self.allow_gen_future.clone(),
556 let pinned_ident = Ident::with_dummy_span(sym::pinned);
557 let (pinned_pat, pinned_pat_hid) =
558 self.pat_ident_binding_mode(span, pinned_ident, hir::BindingAnnotation::Mutable);
560 // ::std::future::poll_with_tls_context(unsafe {
561 // ::std::pin::Pin::new_unchecked(&mut pinned)
564 let pinned = self.expr_ident(span, pinned_ident, pinned_pat_hid);
565 let ref_mut_pinned = self.expr_mut_addr_of(span, pinned);
566 let pin_ty_id = self.next_id();
567 let new_unchecked_expr_kind = self.expr_call_std_assoc_fn(
570 &[sym::pin, sym::Pin],
572 arena_vec![self; ref_mut_pinned],
575 self.arena.alloc(self.expr(span, new_unchecked_expr_kind, ThinVec::new()));
576 let unsafe_expr = self.expr_unsafe(new_unchecked);
577 self.expr_call_std_path(
579 &[sym::future, sym::poll_with_tls_context],
580 arena_vec![self; unsafe_expr],
584 // `::std::task::Poll::Ready(result) => break result`
585 let loop_node_id = self.resolver.next_node_id();
586 let loop_hir_id = self.lower_node_id(loop_node_id);
588 let x_ident = Ident::with_dummy_span(sym::result);
589 let (x_pat, x_pat_hid) = self.pat_ident(span, x_ident);
590 let x_expr = self.expr_ident(span, x_ident, x_pat_hid);
591 let ready_pat = self.pat_std_enum(
593 &[sym::task, sym::Poll, sym::Ready],
594 arena_vec![self; x_pat],
596 let break_x = self.with_loop_scope(loop_node_id, move |this| {
598 hir::ExprKind::Break(this.lower_loop_destination(None), Some(x_expr));
599 this.arena.alloc(this.expr(await_span, expr_break, ThinVec::new()))
601 self.arm(ready_pat, break_x)
604 // `::std::task::Poll::Pending => {}`
606 let pending_pat = self.pat_std_enum(span, &[sym::task, sym::Poll, sym::Pending], &[]);
607 let empty_block = self.expr_block_empty(span);
608 self.arm(pending_pat, empty_block)
611 let inner_match_stmt = {
612 let match_expr = self.expr_match(
615 arena_vec![self; ready_arm, pending_arm],
616 hir::MatchSource::AwaitDesugar,
618 self.stmt_expr(span, match_expr)
622 let unit = self.expr_unit(span);
623 let yield_expr = self.expr(
625 hir::ExprKind::Yield(unit, hir::YieldSource::Await),
628 self.stmt_expr(span, yield_expr)
631 let loop_block = self.block_all(span, arena_vec![self; inner_match_stmt, yield_stmt], None);
634 let loop_expr = self.arena.alloc(hir::Expr {
636 kind: hir::ExprKind::Loop(loop_block, None, hir::LoopSource::Loop),
638 attrs: ThinVec::new(),
641 // mut pinned => loop { ... }
642 let pinned_arm = self.arm(pinned_pat, loop_expr);
645 // mut pinned => loop { .. }
647 let expr = self.lower_expr(expr);
648 hir::ExprKind::Match(expr, arena_vec![self; pinned_arm], hir::MatchSource::AwaitDesugar)
651 fn lower_expr_closure(
653 capture_clause: CaptureBy,
654 movability: Movability,
658 ) -> hir::ExprKind<'hir> {
659 // Lower outside new scope to preserve `is_in_loop_condition`.
660 let fn_decl = self.lower_fn_decl(decl, None, false, None);
662 self.with_new_scopes(move |this| {
663 let prev = this.current_item;
664 this.current_item = Some(fn_decl_span);
665 let mut generator_kind = None;
666 let body_id = this.lower_fn_body(decl, |this| {
667 let e = this.lower_expr_mut(body);
668 generator_kind = this.generator_kind;
671 let generator_option =
672 this.generator_movability_for_fn(&decl, fn_decl_span, generator_kind, movability);
673 this.current_item = prev;
674 hir::ExprKind::Closure(capture_clause, fn_decl, body_id, fn_decl_span, generator_option)
678 fn generator_movability_for_fn(
682 generator_kind: Option<hir::GeneratorKind>,
683 movability: Movability,
684 ) -> Option<hir::Movability> {
685 match generator_kind {
686 Some(hir::GeneratorKind::Gen) => {
687 if !decl.inputs.is_empty() {
692 "generators cannot have explicit parameters"
697 Some(hir::GeneratorKind::Async(_)) => {
698 bug!("non-`async` closure body turned `async` during lowering");
701 if movability == Movability::Static {
702 span_err!(self.sess, fn_decl_span, E0697, "closures cannot be static");
709 fn lower_expr_async_closure(
711 capture_clause: CaptureBy,
716 ) -> hir::ExprKind<'hir> {
718 FnDecl { inputs: decl.inputs.clone(), output: FunctionRetTy::Default(fn_decl_span) };
719 // We need to lower the declaration outside the new scope, because we
720 // have to conserve the state of being inside a loop condition for the
721 // closure argument types.
722 let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None);
724 self.with_new_scopes(move |this| {
725 // FIXME(cramertj): allow `async` non-`move` closures with arguments.
726 if capture_clause == CaptureBy::Ref && !decl.inputs.is_empty() {
731 "`async` non-`move` closures with parameters are not currently supported",
734 "consider using `let` statements to manually capture \
735 variables by reference before entering an `async move` closure",
740 // Transform `async |x: u8| -> X { ... }` into
741 // `|x: u8| future_from_generator(|| -> X { ... })`.
742 let body_id = this.lower_fn_body(&outer_decl, |this| {
744 if let FunctionRetTy::Ty(ty) = &decl.output { Some(ty.clone()) } else { None };
745 let async_body = this.make_async_expr(
750 hir::AsyncGeneratorKind::Closure,
751 |this| this.with_new_scopes(|this| this.lower_expr_mut(body)),
753 this.expr(fn_decl_span, async_body, ThinVec::new())
755 hir::ExprKind::Closure(capture_clause, fn_decl, body_id, fn_decl_span, None)
759 /// Desugar `<start>..=<end>` into `std::ops::RangeInclusive::new(<start>, <end>)`.
760 fn lower_expr_range_closed(&mut self, span: Span, e1: &Expr, e2: &Expr) -> hir::ExprKind<'hir> {
761 let id = self.next_id();
762 let e1 = self.lower_expr_mut(e1);
763 let e2 = self.lower_expr_mut(e2);
764 self.expr_call_std_assoc_fn(
767 &[sym::ops, sym::RangeInclusive],
769 arena_vec![self; e1, e2],
779 ) -> hir::ExprKind<'hir> {
780 use syntax::ast::RangeLimits::*;
782 let path = match (e1, e2, lims) {
783 (None, None, HalfOpen) => sym::RangeFull,
784 (Some(..), None, HalfOpen) => sym::RangeFrom,
785 (None, Some(..), HalfOpen) => sym::RangeTo,
786 (Some(..), Some(..), HalfOpen) => sym::Range,
787 (None, Some(..), Closed) => sym::RangeToInclusive,
788 (Some(..), Some(..), Closed) => unreachable!(),
789 (_, None, Closed) => {
790 self.diagnostic().span_fatal(span, "inclusive range with no end").raise()
794 let fields = self.arena.alloc_from_iter(
795 e1.iter().map(|e| ("start", e)).chain(e2.iter().map(|e| ("end", e))).map(|(s, e)| {
796 let expr = self.lower_expr(&e);
797 let ident = Ident::new(Symbol::intern(s), e.span);
798 self.field(ident, expr, e.span)
802 let is_unit = fields.is_empty();
803 let struct_path = [sym::ops, path];
804 let struct_path = self.std_path(span, &struct_path, None, is_unit);
805 let struct_path = hir::QPath::Resolved(None, struct_path);
808 hir::ExprKind::Path(struct_path)
810 hir::ExprKind::Struct(self.arena.alloc(struct_path), fields, None)
814 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
815 let target_id = match destination {
817 if let Some(loop_id) = self.resolver.get_label_res(id) {
818 Ok(self.lower_node_id(loop_id))
820 Err(hir::LoopIdError::UnresolvedLabel)
827 .map(|id| Ok(self.lower_node_id(id)))
828 .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
831 hir::Destination { label: destination.map(|(_, label)| label), target_id }
834 fn lower_jump_destination(&mut self, id: NodeId, opt_label: Option<Label>) -> hir::Destination {
835 if self.is_in_loop_condition && opt_label.is_none() {
838 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition).into(),
841 self.lower_loop_destination(opt_label.map(|label| (id, label)))
845 fn with_catch_scope<T, F>(&mut self, catch_id: NodeId, f: F) -> T
847 F: FnOnce(&mut Self) -> T,
849 let len = self.catch_scopes.len();
850 self.catch_scopes.push(catch_id);
852 let result = f(self);
855 self.catch_scopes.len(),
856 "catch scopes should be added and removed in stack order"
859 self.catch_scopes.pop().unwrap();
864 fn with_loop_scope<T, F>(&mut self, loop_id: NodeId, f: F) -> T
866 F: FnOnce(&mut Self) -> T,
868 // We're no longer in the base loop's condition; we're in another loop.
869 let was_in_loop_condition = self.is_in_loop_condition;
870 self.is_in_loop_condition = false;
872 let len = self.loop_scopes.len();
873 self.loop_scopes.push(loop_id);
875 let result = f(self);
878 self.loop_scopes.len(),
879 "loop scopes should be added and removed in stack order"
882 self.loop_scopes.pop().unwrap();
884 self.is_in_loop_condition = was_in_loop_condition;
889 fn with_loop_condition_scope<T, F>(&mut self, f: F) -> T
891 F: FnOnce(&mut Self) -> T,
893 let was_in_loop_condition = self.is_in_loop_condition;
894 self.is_in_loop_condition = true;
896 let result = f(self);
898 self.is_in_loop_condition = was_in_loop_condition;
903 fn lower_expr_asm(&mut self, asm: &InlineAsm) -> hir::ExprKind<'hir> {
904 let inner = hir::InlineAsmInner {
905 inputs: asm.inputs.iter().map(|&(ref c, _)| c.clone()).collect(),
909 .map(|out| hir::InlineAsmOutput {
910 constraint: out.constraint.clone(),
912 is_indirect: out.is_indirect,
916 asm: asm.asm.clone(),
917 asm_str_style: asm.asm_str_style,
918 clobbers: asm.clobbers.clone().into(),
919 volatile: asm.volatile,
920 alignstack: asm.alignstack,
921 dialect: asm.dialect,
923 let hir_asm = hir::InlineAsm {
925 inputs_exprs: self.arena.alloc_from_iter(
926 asm.inputs.iter().map(|&(_, ref input)| self.lower_expr_mut(input)),
930 .alloc_from_iter(asm.outputs.iter().map(|out| self.lower_expr_mut(&out.expr))),
932 hir::ExprKind::InlineAsm(self.arena.alloc(hir_asm))
935 fn lower_field(&mut self, f: &Field) -> hir::Field<'hir> {
937 hir_id: self.next_id(),
939 expr: self.lower_expr(&f.expr),
941 is_shorthand: f.is_shorthand,
945 fn lower_expr_yield(&mut self, span: Span, opt_expr: Option<&Expr>) -> hir::ExprKind<'hir> {
946 match self.generator_kind {
947 Some(hir::GeneratorKind::Gen) => {}
948 Some(hir::GeneratorKind::Async(_)) => {
949 span_err!(self.sess, span, E0727, "`async` generators are not yet supported",);
950 return hir::ExprKind::Err;
952 None => self.generator_kind = Some(hir::GeneratorKind::Gen),
956 opt_expr.as_ref().map(|x| self.lower_expr(x)).unwrap_or_else(|| self.expr_unit(span));
958 hir::ExprKind::Yield(expr, hir::YieldSource::Yield)
961 /// Desugar `ExprForLoop` from: `[opt_ident]: for <pat> in <head> <body>` into:
964 /// let result = match ::std::iter::IntoIterator::into_iter(<head>) {
966 /// [opt_ident]: loop {
968 /// match ::std::iter::Iterator::next(&mut iter) {
969 /// ::std::option::Option::Some(val) => __next = val,
970 /// ::std::option::Option::None => break
972 /// let <pat> = __next;
973 /// StmtKind::Expr(<body>);
986 opt_label: Option<Label>,
987 ) -> hir::Expr<'hir> {
989 let mut head = self.lower_expr_mut(head);
990 let desugared_span = self.mark_span_with_reason(DesugaringKind::ForLoop, head.span, None);
991 head.span = desugared_span;
993 let iter = Ident::with_dummy_span(sym::iter);
995 let next_ident = Ident::with_dummy_span(sym::__next);
996 let (next_pat, next_pat_hid) = self.pat_ident_binding_mode(
999 hir::BindingAnnotation::Mutable,
1002 // `::std::option::Option::Some(val) => __next = val`
1004 let val_ident = Ident::with_dummy_span(sym::val);
1005 let (val_pat, val_pat_hid) = self.pat_ident(pat.span, val_ident);
1006 let val_expr = self.expr_ident(pat.span, val_ident, val_pat_hid);
1007 let next_expr = self.expr_ident(pat.span, next_ident, next_pat_hid);
1008 let assign = self.arena.alloc(self.expr(
1010 hir::ExprKind::Assign(next_expr, val_expr, pat.span),
1013 let some_pat = self.pat_some(pat.span, val_pat);
1014 self.arm(some_pat, assign)
1017 // `::std::option::Option::None => break`
1020 self.with_loop_scope(e.id, |this| this.expr_break(e.span, ThinVec::new()));
1021 let pat = self.pat_none(e.span);
1022 self.arm(pat, break_expr)
1026 let (iter_pat, iter_pat_nid) =
1027 self.pat_ident_binding_mode(desugared_span, iter, hir::BindingAnnotation::Mutable);
1029 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
1031 let iter = self.expr_ident(desugared_span, iter, iter_pat_nid);
1032 let ref_mut_iter = self.expr_mut_addr_of(desugared_span, iter);
1033 let next_path = &[sym::iter, sym::Iterator, sym::next];
1035 self.expr_call_std_path(desugared_span, next_path, arena_vec![self; ref_mut_iter]);
1036 let arms = arena_vec![self; pat_arm, break_arm];
1038 self.expr_match(desugared_span, next_expr, arms, hir::MatchSource::ForLoopDesugar)
1040 let match_stmt = self.stmt_expr(desugared_span, match_expr);
1042 let next_expr = self.expr_ident(desugared_span, next_ident, next_pat_hid);
1045 let next_let = self.stmt_let_pat(
1050 hir::LocalSource::ForLoopDesugar,
1053 // `let <pat> = __next`
1054 let pat = self.lower_pat(pat);
1055 let pat_let = self.stmt_let_pat(
1060 hir::LocalSource::ForLoopDesugar,
1063 let body_block = self.with_loop_scope(e.id, |this| this.lower_block(body, false));
1064 let body_expr = self.expr_block(body_block, ThinVec::new());
1065 let body_stmt = self.stmt_expr(body.span, body_expr);
1067 let loop_block = self.block_all(
1069 arena_vec![self; next_let, match_stmt, pat_let, body_stmt],
1073 // `[opt_ident]: loop { ... }`
1074 let kind = hir::ExprKind::Loop(loop_block, opt_label, hir::LoopSource::ForLoop);
1075 let loop_expr = self.arena.alloc(hir::Expr {
1076 hir_id: self.lower_node_id(e.id),
1079 attrs: ThinVec::new(),
1082 // `mut iter => { ... }`
1083 let iter_arm = self.arm(iter_pat, loop_expr);
1085 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
1086 let into_iter_expr = {
1087 let into_iter_path = &[sym::iter, sym::IntoIterator, sym::into_iter];
1088 self.expr_call_std_path(desugared_span, into_iter_path, arena_vec![self; head])
1091 let match_expr = self.arena.alloc(self.expr_match(
1094 arena_vec![self; iter_arm],
1095 hir::MatchSource::ForLoopDesugar,
1098 // This is effectively `{ let _result = ...; _result }`.
1099 // The construct was introduced in #21984 and is necessary to make sure that
1100 // temporaries in the `head` expression are dropped and do not leak to the
1101 // surrounding scope of the `match` since the `match` is not a terminating scope.
1103 // Also, add the attributes to the outer returned expr node.
1104 self.expr_drop_temps_mut(desugared_span, match_expr, e.attrs.clone())
1107 /// Desugar `ExprKind::Try` from: `<expr>?` into:
1109 /// match Try::into_result(<expr>) {
1110 /// Ok(val) => #[allow(unreachable_code)] val,
1111 /// Err(err) => #[allow(unreachable_code)]
1112 /// // If there is an enclosing `try {...}`:
1113 /// break 'catch_target Try::from_error(From::from(err)),
1115 /// return Try::from_error(From::from(err)),
1118 fn lower_expr_try(&mut self, span: Span, sub_expr: &Expr) -> hir::ExprKind<'hir> {
1119 let unstable_span = self.mark_span_with_reason(
1120 DesugaringKind::QuestionMark,
1122 self.allow_try_trait.clone(),
1124 let try_span = self.sess.source_map().end_point(span);
1125 let try_span = self.mark_span_with_reason(
1126 DesugaringKind::QuestionMark,
1128 self.allow_try_trait.clone(),
1131 // `Try::into_result(<expr>)`
1134 let sub_expr = self.lower_expr_mut(sub_expr);
1136 let path = &[sym::ops, sym::Try, sym::into_result];
1137 self.expr_call_std_path(unstable_span, path, arena_vec![self; sub_expr])
1140 // `#[allow(unreachable_code)]`
1142 // `allow(unreachable_code)`
1144 let allow_ident = Ident::new(sym::allow, span);
1145 let uc_ident = Ident::new(sym::unreachable_code, span);
1146 let uc_nested = attr::mk_nested_word_item(uc_ident);
1147 attr::mk_list_item(allow_ident, vec![uc_nested])
1149 attr::mk_attr_outer(allow)
1151 let attrs = vec![attr];
1153 // `Ok(val) => #[allow(unreachable_code)] val,`
1155 let val_ident = Ident::with_dummy_span(sym::val);
1156 let (val_pat, val_pat_nid) = self.pat_ident(span, val_ident);
1157 let val_expr = self.arena.alloc(self.expr_ident_with_attrs(
1161 ThinVec::from(attrs.clone()),
1163 let ok_pat = self.pat_ok(span, val_pat);
1164 self.arm(ok_pat, val_expr)
1167 // `Err(err) => #[allow(unreachable_code)]
1168 // return Try::from_error(From::from(err)),`
1170 let err_ident = Ident::with_dummy_span(sym::err);
1171 let (err_local, err_local_nid) = self.pat_ident(try_span, err_ident);
1173 let from_path = &[sym::convert, sym::From, sym::from];
1174 let err_expr = self.expr_ident_mut(try_span, err_ident, err_local_nid);
1175 self.expr_call_std_path(try_span, from_path, arena_vec![self; err_expr])
1178 self.wrap_in_try_constructor(sym::from_error, unstable_span, from_expr, try_span);
1179 let thin_attrs = ThinVec::from(attrs);
1180 let catch_scope = self.catch_scopes.last().map(|x| *x);
1181 let ret_expr = if let Some(catch_node) = catch_scope {
1182 let target_id = Ok(self.lower_node_id(catch_node));
1183 self.arena.alloc(self.expr(
1185 hir::ExprKind::Break(
1186 hir::Destination { label: None, target_id },
1187 Some(from_err_expr),
1192 self.arena.alloc(self.expr(
1194 hir::ExprKind::Ret(Some(from_err_expr)),
1199 let err_pat = self.pat_err(try_span, err_local);
1200 self.arm(err_pat, ret_expr)
1203 hir::ExprKind::Match(
1205 arena_vec![self; err_arm, ok_arm],
1206 hir::MatchSource::TryDesugar,
1210 // =========================================================================
1211 // Helper methods for building HIR.
1212 // =========================================================================
1214 /// Constructs a `true` or `false` literal expression.
1215 pub(super) fn expr_bool(&mut self, span: Span, val: bool) -> &'hir hir::Expr<'hir> {
1216 let lit = Spanned { span, node: LitKind::Bool(val) };
1217 self.arena.alloc(self.expr(span, hir::ExprKind::Lit(lit), ThinVec::new()))
1220 /// Wrap the given `expr` in a terminating scope using `hir::ExprKind::DropTemps`.
1222 /// In terms of drop order, it has the same effect as wrapping `expr` in
1223 /// `{ let _t = $expr; _t }` but should provide better compile-time performance.
1225 /// The drop order can be important in e.g. `if expr { .. }`.
1226 pub(super) fn expr_drop_temps(
1229 expr: &'hir hir::Expr<'hir>,
1231 ) -> &'hir hir::Expr<'hir> {
1232 self.arena.alloc(self.expr_drop_temps_mut(span, expr, attrs))
1235 pub(super) fn expr_drop_temps_mut(
1238 expr: &'hir hir::Expr<'hir>,
1240 ) -> hir::Expr<'hir> {
1241 self.expr(span, hir::ExprKind::DropTemps(expr), attrs)
1247 arg: &'hir hir::Expr<'hir>,
1248 arms: &'hir [hir::Arm<'hir>],
1249 source: hir::MatchSource,
1250 ) -> hir::Expr<'hir> {
1251 self.expr(span, hir::ExprKind::Match(arg, arms, source), ThinVec::new())
1254 fn expr_break(&mut self, span: Span, attrs: AttrVec) -> &'hir hir::Expr<'hir> {
1255 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
1256 self.arena.alloc(self.expr(span, expr_break, attrs))
1259 fn expr_mut_addr_of(&mut self, span: Span, e: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
1262 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Mut, e),
1267 fn expr_unit(&mut self, sp: Span) -> &'hir hir::Expr<'hir> {
1268 self.arena.alloc(self.expr(sp, hir::ExprKind::Tup(&[]), ThinVec::new()))
1274 e: &'hir hir::Expr<'hir>,
1275 args: &'hir [hir::Expr<'hir>],
1276 ) -> &'hir hir::Expr<'hir> {
1277 self.arena.alloc(self.expr(span, hir::ExprKind::Call(e, args), ThinVec::new()))
1280 // Note: associated functions must use `expr_call_std_path`.
1281 fn expr_call_std_path(
1284 path_components: &[Symbol],
1285 args: &'hir [hir::Expr<'hir>],
1286 ) -> &'hir hir::Expr<'hir> {
1288 self.arena.alloc(self.expr_std_path(span, path_components, None, ThinVec::new()));
1289 self.expr_call(span, path, args)
1292 // Create an expression calling an associated function of an std type.
1294 // Associated functions cannot be resolved through the normal `std_path` function,
1295 // as they are resolved differently and so cannot use `expr_call_std_path`.
1297 // This function accepts the path component (`ty_path_components`) separately from
1298 // the name of the associated function (`assoc_fn_name`) in order to facilitate
1299 // separate resolution of the type and creation of a path referring to its associated
1301 fn expr_call_std_assoc_fn(
1303 ty_path_id: hir::HirId,
1305 ty_path_components: &[Symbol],
1306 assoc_fn_name: &str,
1307 args: &'hir [hir::Expr<'hir>],
1308 ) -> hir::ExprKind<'hir> {
1309 let ty_path = self.std_path(span, ty_path_components, None, false);
1311 self.arena.alloc(self.ty_path(ty_path_id, span, hir::QPath::Resolved(None, ty_path)));
1312 let fn_seg = self.arena.alloc(hir::PathSegment::from_ident(Ident::from_str(assoc_fn_name)));
1313 let fn_path = hir::QPath::TypeRelative(ty, fn_seg);
1315 self.arena.alloc(self.expr(span, hir::ExprKind::Path(fn_path), ThinVec::new()));
1316 hir::ExprKind::Call(fn_expr, args)
1322 components: &[Symbol],
1323 params: Option<&'hir hir::GenericArgs<'hir>>,
1325 ) -> hir::Expr<'hir> {
1326 let path = self.std_path(span, components, params, true);
1327 self.expr(span, hir::ExprKind::Path(hir::QPath::Resolved(None, path)), attrs)
1330 pub(super) fn expr_ident(
1334 binding: hir::HirId,
1335 ) -> &'hir hir::Expr<'hir> {
1336 self.arena.alloc(self.expr_ident_mut(sp, ident, binding))
1339 pub(super) fn expr_ident_mut(
1343 binding: hir::HirId,
1344 ) -> hir::Expr<'hir> {
1345 self.expr_ident_with_attrs(sp, ident, binding, ThinVec::new())
1348 fn expr_ident_with_attrs(
1352 binding: hir::HirId,
1354 ) -> hir::Expr<'hir> {
1355 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
1357 self.arena.alloc(hir::Path {
1359 res: Res::Local(binding),
1360 segments: arena_vec![self; hir::PathSegment::from_ident(ident)],
1364 self.expr(span, expr_path, attrs)
1367 fn expr_unsafe(&mut self, expr: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
1368 let hir_id = self.next_id();
1369 let span = expr.span;
1372 hir::ExprKind::Block(
1373 self.arena.alloc(hir::Block {
1377 rules: hir::UnsafeBlock(hir::CompilerGenerated),
1379 targeted_by_break: false,
1387 fn expr_block_empty(&mut self, span: Span) -> &'hir hir::Expr<'hir> {
1388 let blk = self.block_all(span, &[], None);
1389 let expr = self.expr_block(blk, ThinVec::new());
1390 self.arena.alloc(expr)
1393 pub(super) fn expr_block(
1395 b: &'hir hir::Block<'hir>,
1397 ) -> hir::Expr<'hir> {
1398 self.expr(b.span, hir::ExprKind::Block(b, None), attrs)
1404 kind: hir::ExprKind<'hir>,
1406 ) -> hir::Expr<'hir> {
1407 hir::Expr { hir_id: self.next_id(), kind, span, attrs }
1410 fn field(&mut self, ident: Ident, expr: &'hir hir::Expr<'hir>, span: Span) -> hir::Field<'hir> {
1411 hir::Field { hir_id: self.next_id(), ident, span, expr, is_shorthand: false }
1414 fn arm(&mut self, pat: &'hir hir::Pat<'hir>, expr: &'hir hir::Expr<'hir>) -> hir::Arm<'hir> {
1416 hir_id: self.next_id(),