1use std::mem;
2use std::ops::ControlFlow;
3use std::sync::Arc;
4
5use rustc_ast::*;
6use rustc_ast_pretty::pprust::expr_to_string;
7use rustc_data_structures::stack::ensure_sufficient_stack;
8use rustc_errors::msg;
9use rustc_hir as hir;
10use rustc_hir::def::{DefKind, Res};
11use rustc_hir::{HirId, Target, find_attr};
12use rustc_middle::span_bug;
13use rustc_middle::ty::TyCtxt;
14use rustc_session::errors::report_lit_error;
15use rustc_span::{ByteSymbol, DUMMY_SP, DesugaringKind, Ident, Span, Spanned, Symbol, respan, sym};
16use thin_vec::{ThinVec, thin_vec};
17use visit::{Visitor, walk_expr};
18
19use super::errors::{
20 AsyncCoroutinesNotSupported, AwaitOnlyInAsyncFnAndBlocks, ClosureCannotBeStatic,
21 CoroutineTooManyParameters, FunctionalRecordUpdateDestructuringAssignment,
22 InclusiveRangeWithNoEnd, MatchArmWithNoBody, NeverPatternWithBody, NeverPatternWithGuard,
23 UnderscoreExprLhsAssign,
24};
25use super::{
26 GenericArgsMode, ImplTraitContext, LoweringContext, ParamMode, ResolverAstLoweringExt,
27};
28use crate::errors::{InvalidLegacyConstGenericArg, UseConstGenericArg, YieldInClosure};
29use crate::{AllowReturnTypeNotation, FnDeclKind, ImplTraitPosition, TryBlockScope};
30
31pub(super) struct WillCreateDefIdsVisitor;
32
33impl<'v> rustc_ast::visit::Visitor<'v> for WillCreateDefIdsVisitor {
34 type Result = ControlFlow<Span>;
35
36 fn visit_anon_const(&mut self, c: &'v AnonConst) -> Self::Result {
37 ControlFlow::Break(c.value.span)
38 }
39
40 fn visit_item(&mut self, item: &'v Item) -> Self::Result {
41 ControlFlow::Break(item.span)
42 }
43
44 fn visit_expr(&mut self, ex: &'v Expr) -> Self::Result {
45 match ex.kind {
46 ExprKind::Gen(..) | ExprKind::ConstBlock(..) | ExprKind::Closure(..) => {
47 ControlFlow::Break(ex.span)
48 }
49 _ => walk_expr(self, ex),
50 }
51 }
52}
53
54impl<'hir> LoweringContext<'_, 'hir> {
55 fn lower_exprs(&mut self, exprs: &[Box<Expr>]) -> &'hir [hir::Expr<'hir>] {
56 self.arena.alloc_from_iter(exprs.iter().map(|x| self.lower_expr_mut(x)))
57 }
58
59 pub(super) fn lower_expr(&mut self, e: &Expr) -> &'hir hir::Expr<'hir> {
60 self.arena.alloc(self.lower_expr_mut(e))
61 }
62
63 pub(super) fn lower_expr_mut(&mut self, e: &Expr) -> hir::Expr<'hir> {
64 ensure_sufficient_stack(|| {
65 let mut span = self.lower_span(e.span);
66 match &e.kind {
67 ExprKind::Paren(ex) => {
69 let mut ex = self.lower_expr_mut(ex);
70 if e.span.contains(ex.span) {
72 ex.span = self.lower_span(e.span.with_ctxt(ex.span.ctxt()));
73 }
74 if !e.attrs.is_empty() {
76 let old_attrs = self.attrs.get(&ex.hir_id.local_id).copied().unwrap_or(&[]);
77 let new_attrs = self
78 .lower_attrs_vec(&e.attrs, e.span, ex.hir_id, Target::from_expr(e))
79 .into_iter()
80 .chain(old_attrs.iter().cloned());
81 let new_attrs = &*self.arena.alloc_from_iter(new_attrs);
82 if new_attrs.is_empty() {
83 return ex;
84 }
85 self.attrs.insert(ex.hir_id.local_id, new_attrs);
86 }
87 return ex;
88 }
89 ExprKind::ForLoop { pat, iter, body, label, kind } => {
95 return self.lower_expr_for(e, pat, iter, body, *label, *kind);
96 }
97 _ => (),
98 }
99
100 let expr_hir_id = self.lower_node_id(e.id);
101 let attrs = self.lower_attrs(expr_hir_id, &e.attrs, e.span, Target::from_expr(e));
102
103 let kind = match &e.kind {
104 ExprKind::Array(exprs) => hir::ExprKind::Array(self.lower_exprs(exprs)),
105 ExprKind::ConstBlock(c) => hir::ExprKind::ConstBlock(self.lower_const_block(c)),
106 ExprKind::Repeat(expr, count) => {
107 let expr = self.lower_expr(expr);
108 let count = self.lower_array_length_to_const_arg(count);
109 hir::ExprKind::Repeat(expr, count)
110 }
111 ExprKind::Tup(elts) => hir::ExprKind::Tup(self.lower_exprs(elts)),
112 ExprKind::Call(f, args) => {
113 if let Some(legacy_args) = self.resolver.legacy_const_generic_args(f, self.tcx)
114 {
115 self.lower_legacy_const_generics((**f).clone(), args.clone(), &legacy_args)
116 } else {
117 let f = self.lower_expr(f);
118 hir::ExprKind::Call(f, self.lower_exprs(args))
119 }
120 }
121 ExprKind::MethodCall(box MethodCall { seg, receiver, args, span }) => {
122 let hir_seg = self.arena.alloc(self.lower_path_segment(
123 e.span,
124 seg,
125 ParamMode::Optional,
126 GenericArgsMode::Err,
127 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
128 None,
130 ));
131 let receiver = self.lower_expr(receiver);
132 let args =
133 self.arena.alloc_from_iter(args.iter().map(|x| self.lower_expr_mut(x)));
134 hir::ExprKind::MethodCall(hir_seg, receiver, args, self.lower_span(*span))
135 }
136 ExprKind::Binary(binop, lhs, rhs) => {
137 let binop = self.lower_binop(*binop);
138 let lhs = self.lower_expr(lhs);
139 let rhs = self.lower_expr(rhs);
140 hir::ExprKind::Binary(binop, lhs, rhs)
141 }
142 ExprKind::Unary(op, ohs) => {
143 let op = self.lower_unop(*op);
144 let ohs = self.lower_expr(ohs);
145 hir::ExprKind::Unary(op, ohs)
146 }
147 ExprKind::Lit(token_lit) => hir::ExprKind::Lit(self.lower_lit(token_lit, e.span)),
148 ExprKind::IncludedBytes(byte_sym) => {
149 let lit = respan(
150 self.lower_span(e.span),
151 LitKind::ByteStr(*byte_sym, StrStyle::Cooked),
152 );
153 hir::ExprKind::Lit(lit)
154 }
155 ExprKind::Cast(expr, ty) => {
156 let expr = self.lower_expr(expr);
157 let ty = self
158 .lower_ty_alloc(ty, ImplTraitContext::Disallowed(ImplTraitPosition::Cast));
159 hir::ExprKind::Cast(expr, ty)
160 }
161 ExprKind::Type(expr, ty) => {
162 let expr = self.lower_expr(expr);
163 let ty = self
164 .lower_ty_alloc(ty, ImplTraitContext::Disallowed(ImplTraitPosition::Cast));
165 hir::ExprKind::Type(expr, ty)
166 }
167 ExprKind::AddrOf(k, m, ohs) => {
168 let ohs = self.lower_expr(ohs);
169 hir::ExprKind::AddrOf(*k, *m, ohs)
170 }
171 ExprKind::Let(pat, scrutinee, span, recovered) => {
172 hir::ExprKind::Let(self.arena.alloc(hir::LetExpr {
173 span: self.lower_span(*span),
174 pat: self.lower_pat(pat),
175 ty: None,
176 init: self.lower_expr(scrutinee),
177 recovered: *recovered,
178 }))
179 }
180 ExprKind::If(cond, then, else_opt) => {
181 self.lower_expr_if(cond, then, else_opt.as_deref())
182 }
183 ExprKind::While(cond, body, opt_label) => {
184 self.with_loop_scope(expr_hir_id, |this| {
185 let span =
186 this.mark_span_with_reason(DesugaringKind::WhileLoop, e.span, None);
187 let opt_label = this.lower_label(*opt_label, e.id, expr_hir_id);
188 this.lower_expr_while_in_loop_scope(span, cond, body, opt_label)
189 })
190 }
191 ExprKind::Loop(body, opt_label, span) => {
192 self.with_loop_scope(expr_hir_id, |this| {
193 let opt_label = this.lower_label(*opt_label, e.id, expr_hir_id);
194 hir::ExprKind::Loop(
195 this.lower_block(body, false),
196 opt_label,
197 hir::LoopSource::Loop,
198 this.lower_span(*span),
199 )
200 })
201 }
202 ExprKind::TryBlock(body, opt_ty) => {
203 self.lower_expr_try_block(body, opt_ty.as_deref())
204 }
205 ExprKind::Match(expr, arms, kind) => hir::ExprKind::Match(
206 self.lower_expr(expr),
207 self.arena.alloc_from_iter(arms.iter().map(|x| self.lower_arm(x))),
208 match kind {
209 MatchKind::Prefix => hir::MatchSource::Normal,
210 MatchKind::Postfix => hir::MatchSource::Postfix,
211 },
212 ),
213 ExprKind::Await(expr, await_kw_span) => self.lower_expr_await(*await_kw_span, expr),
214 ExprKind::Use(expr, use_kw_span) => self.lower_expr_use(*use_kw_span, expr),
215 ExprKind::Closure(box Closure {
216 binder,
217 capture_clause,
218 constness,
219 coroutine_kind,
220 movability,
221 fn_decl,
222 body,
223 fn_decl_span,
224 fn_arg_span,
225 }) => match coroutine_kind {
226 Some(coroutine_kind) => self.lower_expr_coroutine_closure(
227 binder,
228 *capture_clause,
229 e.id,
230 expr_hir_id,
231 *coroutine_kind,
232 *constness,
233 fn_decl,
234 body,
235 *fn_decl_span,
236 *fn_arg_span,
237 ),
238 None => self.lower_expr_closure(
239 attrs,
240 binder,
241 *capture_clause,
242 e.id,
243 *constness,
244 *movability,
245 fn_decl,
246 body,
247 *fn_decl_span,
248 *fn_arg_span,
249 ),
250 },
251 ExprKind::Gen(capture_clause, block, genblock_kind, decl_span) => {
252 let desugaring_kind = match genblock_kind {
253 GenBlockKind::Async => hir::CoroutineDesugaring::Async,
254 GenBlockKind::Gen => hir::CoroutineDesugaring::Gen,
255 GenBlockKind::AsyncGen => hir::CoroutineDesugaring::AsyncGen,
256 };
257 self.make_desugared_coroutine_expr(
258 *capture_clause,
259 e.id,
260 None,
261 *decl_span,
262 e.span,
263 desugaring_kind,
264 hir::CoroutineSource::Block,
265 |this| this.with_new_scopes(e.span, |this| this.lower_block_expr(block)),
266 )
267 }
268 ExprKind::Block(blk, opt_label) => {
269 let block_hir_id = self.lower_node_id(blk.id);
272 let opt_label = self.lower_label(*opt_label, blk.id, block_hir_id);
273 let hir_block = self.arena.alloc(self.lower_block_noalloc(
274 block_hir_id,
275 blk,
276 opt_label.is_some(),
277 ));
278 hir::ExprKind::Block(hir_block, opt_label)
279 }
280 ExprKind::Assign(el, er, span) => self.lower_expr_assign(el, er, *span, e.span),
281 ExprKind::AssignOp(op, el, er) => hir::ExprKind::AssignOp(
282 self.lower_assign_op(*op),
283 self.lower_expr(el),
284 self.lower_expr(er),
285 ),
286 ExprKind::Field(el, ident) => {
287 hir::ExprKind::Field(self.lower_expr(el), self.lower_ident(*ident))
288 }
289 ExprKind::Index(el, er, brackets_span) => hir::ExprKind::Index(
290 self.lower_expr(el),
291 self.lower_expr(er),
292 self.lower_span(*brackets_span),
293 ),
294 ExprKind::Range(e1, e2, lims) => {
295 span = self.mark_span_with_reason(DesugaringKind::RangeExpr, span, None);
296 self.lower_expr_range(span, e1.as_deref(), e2.as_deref(), *lims)
297 }
298 ExprKind::Underscore => {
299 let guar = self.dcx().emit_err(UnderscoreExprLhsAssign { span: e.span });
300 hir::ExprKind::Err(guar)
301 }
302 ExprKind::Path(qself, path) => {
303 let qpath = self.lower_qpath(
304 e.id,
305 qself,
306 path,
307 ParamMode::Optional,
308 AllowReturnTypeNotation::No,
309 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
310 None,
311 );
312 hir::ExprKind::Path(qpath)
313 }
314 ExprKind::Break(opt_label, opt_expr) => {
315 let opt_expr = opt_expr.as_ref().map(|x| self.lower_expr(x));
316 hir::ExprKind::Break(self.lower_jump_destination(e.id, *opt_label), opt_expr)
317 }
318 ExprKind::Continue(opt_label) => {
319 hir::ExprKind::Continue(self.lower_jump_destination(e.id, *opt_label))
320 }
321 ExprKind::Ret(e) => {
322 let expr = e.as_ref().map(|x| self.lower_expr(x));
323 self.checked_return(expr)
324 }
325 ExprKind::Yeet(sub_expr) => self.lower_expr_yeet(e.span, sub_expr.as_deref()),
326 ExprKind::Become(sub_expr) => {
327 let sub_expr = self.lower_expr(sub_expr);
328 hir::ExprKind::Become(sub_expr)
329 }
330 ExprKind::InlineAsm(asm) => {
331 hir::ExprKind::InlineAsm(self.lower_inline_asm(e.span, asm))
332 }
333 ExprKind::FormatArgs(fmt) => self.lower_format_args(e.span, fmt),
334 ExprKind::OffsetOf(container, fields) => hir::ExprKind::OffsetOf(
335 self.lower_ty_alloc(
336 container,
337 ImplTraitContext::Disallowed(ImplTraitPosition::OffsetOf),
338 ),
339 self.arena.alloc_from_iter(fields.iter().map(|&ident| self.lower_ident(ident))),
340 ),
341 ExprKind::Struct(se) => {
342 let rest = match se.rest {
343 StructRest::Base(ref e) => hir::StructTailExpr::Base(self.lower_expr(e)),
344 StructRest::Rest(sp) => {
345 hir::StructTailExpr::DefaultFields(self.lower_span(sp))
346 }
347 StructRest::None => hir::StructTailExpr::None,
348 StructRest::NoneWithError(guar) => hir::StructTailExpr::NoneWithError(guar),
349 };
350 hir::ExprKind::Struct(
351 self.arena.alloc(self.lower_qpath(
352 e.id,
353 &se.qself,
354 &se.path,
355 ParamMode::Optional,
356 AllowReturnTypeNotation::No,
357 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
358 None,
359 )),
360 self.arena
361 .alloc_from_iter(se.fields.iter().map(|x| self.lower_expr_field(x))),
362 rest,
363 )
364 }
365 ExprKind::Yield(kind) => self.lower_expr_yield(e.span, kind.expr().map(|x| &**x)),
366 ExprKind::Err(guar) => hir::ExprKind::Err(*guar),
367
368 ExprKind::UnsafeBinderCast(kind, expr, ty) => hir::ExprKind::UnsafeBinderCast(
369 *kind,
370 self.lower_expr(expr),
371 ty.as_ref().map(|ty| {
372 self.lower_ty_alloc(
373 ty,
374 ImplTraitContext::Disallowed(ImplTraitPosition::Cast),
375 )
376 }),
377 ),
378
379 ExprKind::Dummy => {
380 ::rustc_middle::util::bug::span_bug_fmt(e.span,
format_args!("lowered ExprKind::Dummy"))span_bug!(e.span, "lowered ExprKind::Dummy")
381 }
382
383 ExprKind::Try(sub_expr) => self.lower_expr_try(e.span, sub_expr),
384
385 ExprKind::Paren(_) | ExprKind::ForLoop { .. } => {
386 {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("already handled")));
}unreachable!("already handled")
387 }
388
389 ExprKind::MacCall(_) => {
::core::panicking::panic_fmt(format_args!("{0:?} shouldn\'t exist here",
e.span));
}panic!("{:?} shouldn't exist here", e.span),
390 };
391
392 hir::Expr { hir_id: expr_hir_id, kind, span }
393 })
394 }
395
396 pub(crate) fn lower_const_block(&mut self, c: &AnonConst) -> hir::ConstBlock {
397 self.with_new_scopes(c.value.span, |this| {
398 let def_id = this.local_def_id(c.id);
399 hir::ConstBlock {
400 def_id,
401 hir_id: this.lower_node_id(c.id),
402 body: this.lower_const_body(c.value.span, Some(&c.value)),
403 }
404 })
405 }
406
407 pub(crate) fn lower_lit(&mut self, token_lit: &token::Lit, span: Span) -> hir::Lit {
408 let lit_kind = match LitKind::from_token_lit(*token_lit) {
409 Ok(lit_kind) => lit_kind,
410 Err(err) => {
411 let guar = report_lit_error(&self.tcx.sess.psess, err, *token_lit, span);
412 LitKind::Err(guar)
413 }
414 };
415 respan(self.lower_span(span), lit_kind)
416 }
417
418 fn lower_unop(&mut self, u: UnOp) -> hir::UnOp {
419 match u {
420 UnOp::Deref => hir::UnOp::Deref,
421 UnOp::Not => hir::UnOp::Not,
422 UnOp::Neg => hir::UnOp::Neg,
423 }
424 }
425
426 fn lower_binop(&mut self, b: BinOp) -> BinOp {
427 Spanned { node: b.node, span: self.lower_span(b.span) }
428 }
429
430 fn lower_assign_op(&mut self, a: AssignOp) -> AssignOp {
431 Spanned { node: a.node, span: self.lower_span(a.span) }
432 }
433
434 fn lower_legacy_const_generics(
435 &mut self,
436 mut f: Expr,
437 args: ThinVec<Box<Expr>>,
438 legacy_args_idx: &[usize],
439 ) -> hir::ExprKind<'hir> {
440 let ExprKind::Path(None, path) = &mut f.kind else {
441 ::core::panicking::panic("internal error: entered unreachable code");unreachable!();
442 };
443
444 let mut error = None;
445 let mut invalid_expr_error = |tcx: TyCtxt<'_>, span| {
446 if error.is_none() {
448 let mut const_args = ::alloc::vec::Vec::new()vec![];
449 let mut other_args = ::alloc::vec::Vec::new()vec![];
450 for (idx, arg) in args.iter().enumerate() {
451 if legacy_args_idx.contains(&idx) {
452 const_args.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{{ {0} }}", expr_to_string(arg)))
})format!("{{ {} }}", expr_to_string(arg)));
453 } else {
454 other_args.push(expr_to_string(arg));
455 }
456 }
457 let suggestion = UseConstGenericArg {
458 end_of_fn: f.span.shrink_to_hi(),
459 const_args: const_args.join(", "),
460 other_args: other_args.join(", "),
461 call_args: args[0].span.to(args.last().unwrap().span),
462 };
463 error = Some(tcx.dcx().emit_err(InvalidLegacyConstGenericArg { span, suggestion }));
464 }
465 error.unwrap()
466 };
467
468 let mut real_args = ::alloc::vec::Vec::new()vec![];
470 let mut generic_args = ThinVec::new();
471 for (idx, arg) in args.iter().cloned().enumerate() {
472 if legacy_args_idx.contains(&idx) {
473 let node_id = self.next_node_id();
474 self.create_def(node_id, None, DefKind::AnonConst, f.span);
475 let const_value =
476 if let ControlFlow::Break(span) = WillCreateDefIdsVisitor.visit_expr(&arg) {
477 Box::new(Expr {
478 id: self.next_node_id(),
479 kind: ExprKind::Err(invalid_expr_error(self.tcx, span)),
480 span: f.span,
481 attrs: [].into(),
482 tokens: None,
483 })
484 } else {
485 arg
486 };
487
488 let anon_const = AnonConst {
489 id: node_id,
490 value: const_value,
491 mgca_disambiguation: MgcaDisambiguation::AnonConst,
492 };
493 generic_args.push(AngleBracketedArg::Arg(GenericArg::Const(anon_const)));
494 } else {
495 real_args.push(arg);
496 }
497 }
498
499 let last_segment = path.segments.last_mut().unwrap();
501 if !last_segment.args.is_none() {
::core::panicking::panic("assertion failed: last_segment.args.is_none()")
};assert!(last_segment.args.is_none());
502 last_segment.args = Some(Box::new(GenericArgs::AngleBracketed(AngleBracketedArgs {
503 span: DUMMY_SP,
504 args: generic_args,
505 })));
506
507 let f = self.lower_expr(&f);
509 hir::ExprKind::Call(f, self.lower_exprs(&real_args))
510 }
511
512 fn lower_expr_if(
513 &mut self,
514 cond: &Expr,
515 then: &Block,
516 else_opt: Option<&Expr>,
517 ) -> hir::ExprKind<'hir> {
518 let lowered_cond = self.lower_expr(cond);
519 let then_expr = self.lower_block_expr(then);
520 if let Some(rslt) = else_opt {
521 hir::ExprKind::If(
522 lowered_cond,
523 self.arena.alloc(then_expr),
524 Some(self.lower_expr(rslt)),
525 )
526 } else {
527 hir::ExprKind::If(lowered_cond, self.arena.alloc(then_expr), None)
528 }
529 }
530
531 fn lower_expr_while_in_loop_scope(
548 &mut self,
549 span: Span,
550 cond: &Expr,
551 body: &Block,
552 opt_label: Option<Label>,
553 ) -> hir::ExprKind<'hir> {
554 let lowered_cond = self.with_loop_condition_scope(|t| t.lower_expr(cond));
555 let then = self.lower_block_expr(body);
556 let expr_break = self.expr_break(span);
557 let stmt_break = self.stmt_expr(span, expr_break);
558 let else_blk = self.block_all(span, self.arena.alloc_from_iter([stmt_break])arena_vec![self; stmt_break], None);
559 let else_expr = self.arena.alloc(self.expr_block(else_blk));
560 let if_kind = hir::ExprKind::If(lowered_cond, self.arena.alloc(then), Some(else_expr));
561 let if_expr = self.expr(span, if_kind);
562 let block = self.block_expr(self.arena.alloc(if_expr));
563 let span = self.lower_span(span.with_hi(cond.span.hi()));
564 hir::ExprKind::Loop(block, opt_label, hir::LoopSource::While, span)
565 }
566
567 fn lower_expr_try_block(&mut self, body: &Block, opt_ty: Option<&Ty>) -> hir::ExprKind<'hir> {
571 let body_hir_id = self.lower_node_id(body.id);
572 let new_scope = if opt_ty.is_some() {
573 TryBlockScope::Heterogeneous(body_hir_id)
574 } else {
575 TryBlockScope::Homogeneous(body_hir_id)
576 };
577 let whole_block = self.with_try_block_scope(new_scope, |this| {
578 let mut block = this.lower_block_noalloc(body_hir_id, body, true);
579
580 let (try_span, tail_expr) = if let Some(expr) = block.expr.take() {
582 (
583 this.mark_span_with_reason(
584 DesugaringKind::TryBlock,
585 expr.span,
586 Some(Arc::clone(&this.allow_try_trait)),
587 ),
588 expr,
589 )
590 } else {
591 let try_span = this.mark_span_with_reason(
592 DesugaringKind::TryBlock,
593 this.tcx.sess.source_map().end_point(body.span),
594 Some(Arc::clone(&this.allow_try_trait)),
595 );
596
597 (try_span, this.expr_unit(try_span))
598 };
599
600 let ok_wrapped_span =
601 this.mark_span_with_reason(DesugaringKind::TryBlock, tail_expr.span, None);
602
603 block.expr = Some(this.wrap_in_try_constructor(
605 hir::LangItem::TryTraitFromOutput,
606 try_span,
607 tail_expr,
608 ok_wrapped_span,
609 ));
610
611 this.arena.alloc(block)
612 });
613
614 if let Some(ty) = opt_ty {
615 let ty = self.lower_ty_alloc(ty, ImplTraitContext::Disallowed(ImplTraitPosition::Path));
616 let block_expr = self.arena.alloc(self.expr_block(whole_block));
617 hir::ExprKind::Type(block_expr, ty)
618 } else {
619 hir::ExprKind::Block(whole_block, None)
620 }
621 }
622
623 fn wrap_in_try_constructor(
624 &mut self,
625 lang_item: hir::LangItem,
626 method_span: Span,
627 expr: &'hir hir::Expr<'hir>,
628 overall_span: Span,
629 ) -> &'hir hir::Expr<'hir> {
630 let constructor = self.arena.alloc(self.expr_lang_item_path(method_span, lang_item));
631 self.expr_call(overall_span, constructor, std::slice::from_ref(expr))
632 }
633
634 fn lower_arm(&mut self, arm: &Arm) -> hir::Arm<'hir> {
635 let pat = self.lower_pat(&arm.pat);
636 let guard = arm.guard.as_ref().map(|guard| self.lower_expr(&guard.cond));
637 let hir_id = self.next_id();
638 let span = self.lower_span(arm.span);
639 self.lower_attrs(hir_id, &arm.attrs, arm.span, Target::Arm);
640 let is_never_pattern = pat.is_never_pattern();
641 let body = arm.body.as_ref().map(|x| self.lower_expr(x));
644 let body = if let Some(body) = body
645 && !is_never_pattern
646 {
647 body
648 } else {
649 if !is_never_pattern {
651 if self.tcx.features().never_patterns() {
652 let suggestion = span.shrink_to_hi();
654 self.dcx().emit_err(MatchArmWithNoBody { span, suggestion });
655 }
656 } else if let Some(body) = &arm.body {
657 self.dcx().emit_err(NeverPatternWithBody { span: body.span });
658 } else if let Some(g) = &arm.guard {
659 self.dcx().emit_err(NeverPatternWithGuard { span: g.span() });
660 }
661
662 let block = self.arena.alloc(hir::Block {
665 stmts: &[],
666 expr: None,
667 hir_id: self.next_id(),
668 rules: hir::BlockCheckMode::DefaultBlock,
669 span,
670 targeted_by_break: false,
671 });
672 self.arena.alloc(hir::Expr {
673 hir_id: self.next_id(),
674 kind: hir::ExprKind::Loop(block, None, hir::LoopSource::Loop, span),
675 span,
676 })
677 };
678 hir::Arm { hir_id, pat, guard, body, span }
679 }
680
681 fn lower_capture_clause(&mut self, capture_clause: CaptureBy) -> CaptureBy {
682 match capture_clause {
683 CaptureBy::Ref => CaptureBy::Ref,
684 CaptureBy::Use { use_kw } => CaptureBy::Use { use_kw: self.lower_span(use_kw) },
685 CaptureBy::Value { move_kw } => CaptureBy::Value { move_kw: self.lower_span(move_kw) },
686 }
687 }
688
689 pub(super) fn make_desugared_coroutine_expr(
701 &mut self,
702 capture_clause: CaptureBy,
703 closure_node_id: NodeId,
704 return_ty: Option<hir::FnRetTy<'hir>>,
705 fn_decl_span: Span,
706 span: Span,
707 desugaring_kind: hir::CoroutineDesugaring,
708 coroutine_source: hir::CoroutineSource,
709 body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
710 ) -> hir::ExprKind<'hir> {
711 let closure_def_id = self.local_def_id(closure_node_id);
712 let coroutine_kind = hir::CoroutineKind::Desugared(desugaring_kind, coroutine_source);
713
714 let (inputs, params, task_context): (&[_], &[_], _) = match desugaring_kind {
717 hir::CoroutineDesugaring::Async | hir::CoroutineDesugaring::AsyncGen => {
718 let unstable_span = self.mark_span_with_reason(
720 DesugaringKind::Async,
721 self.lower_span(span),
722 Some(Arc::clone(&self.allow_gen_future)),
723 );
724 let resume_ty =
725 self.make_lang_item_qpath(hir::LangItem::ResumeTy, unstable_span, None);
726 let input_ty = hir::Ty {
727 hir_id: self.next_id(),
728 kind: hir::TyKind::Path(resume_ty),
729 span: unstable_span,
730 };
731 let inputs = self.arena.alloc_from_iter([input_ty])arena_vec![self; input_ty];
732
733 let (pat, task_context_hid) = self.pat_ident_binding_mode(
735 span,
736 Ident::with_dummy_span(sym::_task_context),
737 hir::BindingMode::MUT,
738 );
739 let param = hir::Param {
740 hir_id: self.next_id(),
741 pat,
742 ty_span: self.lower_span(span),
743 span: self.lower_span(span),
744 };
745 let params = self.arena.alloc_from_iter([param])arena_vec![self; param];
746
747 (inputs, params, Some(task_context_hid))
748 }
749 hir::CoroutineDesugaring::Gen => (&[], &[], None),
750 };
751
752 let output =
753 return_ty.unwrap_or_else(|| hir::FnRetTy::DefaultReturn(self.lower_span(span)));
754
755 let fn_decl = self.arena.alloc(hir::FnDecl {
756 inputs,
757 output,
758 fn_decl_kind: hir::FnDeclFlags::default(),
759 });
760
761 let body = self.lower_body(move |this| {
762 this.coroutine_kind = Some(coroutine_kind);
763
764 let old_ctx = this.task_context;
765 if task_context.is_some() {
766 this.task_context = task_context;
767 }
768 let res = body(this);
769 this.task_context = old_ctx;
770
771 (params, res)
772 });
773
774 hir::ExprKind::Closure(self.arena.alloc(hir::Closure {
776 def_id: closure_def_id,
777 binder: hir::ClosureBinder::Default,
778 capture_clause: self.lower_capture_clause(capture_clause),
779 bound_generic_params: &[],
780 fn_decl,
781 body,
782 fn_decl_span: self.lower_span(fn_decl_span),
783 fn_arg_span: None,
784 kind: hir::ClosureKind::Coroutine(coroutine_kind),
785 constness: hir::Constness::NotConst,
786 }))
787 }
788
789 pub(super) fn maybe_forward_track_caller(
792 &mut self,
793 span: Span,
794 outer_hir_id: HirId,
795 inner_hir_id: HirId,
796 ) {
797 if self.tcx.features().async_fn_track_caller()
798 && let Some(attrs) = self.attrs.get(&outer_hir_id.local_id)
799 && {
{
'done:
{
for i in *attrs {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(TrackCaller(_)) => {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()
}find_attr!(*attrs, TrackCaller(_))
800 {
801 let unstable_span = self.mark_span_with_reason(
802 DesugaringKind::Async,
803 span,
804 Some(Arc::clone(&self.allow_gen_future)),
805 );
806 self.lower_attrs(
807 inner_hir_id,
808 &[Attribute {
809 kind: AttrKind::Normal(Box::new(NormalAttr::from_ident(Ident::new(
810 sym::track_caller,
811 span,
812 )))),
813 id: self.tcx.sess.psess.attr_id_generator.mk_attr_id(),
814 style: AttrStyle::Outer,
815 span: unstable_span,
816 }],
817 span,
818 Target::Fn,
819 );
820 }
821 }
822
823 fn lower_expr_await(&mut self, await_kw_span: Span, expr: &Expr) -> hir::ExprKind<'hir> {
839 let expr = self.arena.alloc(self.lower_expr_mut(expr));
840 self.make_lowered_await(await_kw_span, expr, FutureKind::Future)
841 }
842
843 fn make_lowered_await(
845 &mut self,
846 await_kw_span: Span,
847 expr: &'hir hir::Expr<'hir>,
848 await_kind: FutureKind,
849 ) -> hir::ExprKind<'hir> {
850 let full_span = expr.span.to(await_kw_span);
851
852 let is_async_gen = match self.coroutine_kind {
853 Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => false,
854 Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _)) => true,
855 Some(hir::CoroutineKind::Coroutine(_))
856 | Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _))
857 | None => {
858 let stmt_id = self.next_id();
861 let expr_err = self.expr(
862 expr.span,
863 hir::ExprKind::Err(self.dcx().emit_err(AwaitOnlyInAsyncFnAndBlocks {
864 await_kw_span,
865 item_span: self.current_item,
866 })),
867 );
868 return hir::ExprKind::Block(
869 self.block_all(
870 expr.span,
871 self.arena.alloc_from_iter([hir::Stmt {
hir_id: stmt_id,
kind: hir::StmtKind::Semi(expr),
span: expr.span,
}])arena_vec![self; hir::Stmt {
872 hir_id: stmt_id,
873 kind: hir::StmtKind::Semi(expr),
874 span: expr.span,
875 }],
876 Some(self.arena.alloc(expr_err)),
877 ),
878 None,
879 );
880 }
881 };
882
883 let features = match await_kind {
884 FutureKind::Future if is_async_gen => Some(Arc::clone(&self.allow_async_gen)),
885 FutureKind::Future => None,
886 FutureKind::AsyncIterator => Some(Arc::clone(&self.allow_for_await)),
887 };
888 let span = self.mark_span_with_reason(DesugaringKind::Await, await_kw_span, features);
889 let gen_future_span = self.mark_span_with_reason(
890 DesugaringKind::Await,
891 full_span,
892 Some(Arc::clone(&self.allow_gen_future)),
893 );
894 let expr_hir_id = expr.hir_id;
895
896 let awaitee_ident = Ident::with_dummy_span(sym::__awaitee);
900 let (awaitee_pat, awaitee_pat_hid) =
901 self.pat_ident_binding_mode(gen_future_span, awaitee_ident, hir::BindingMode::MUT);
902
903 let task_context_ident = Ident::with_dummy_span(sym::_task_context);
904
905 let poll_expr = {
912 let awaitee = self.expr_ident(span, awaitee_ident, awaitee_pat_hid);
913 let ref_mut_awaitee = self.expr_mut_addr_of(span, awaitee);
914
915 let Some(task_context_hid) = self.task_context else {
916 {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("use of `await` outside of an async context.")));
};unreachable!("use of `await` outside of an async context.");
917 };
918
919 let task_context = self.expr_ident_mut(span, task_context_ident, task_context_hid);
920
921 let new_unchecked = self.expr_call_lang_item_fn_mut(
922 span,
923 hir::LangItem::PinNewUnchecked,
924 self.arena.alloc_from_iter([ref_mut_awaitee])arena_vec![self; ref_mut_awaitee],
925 );
926 let get_context = self.expr_call_lang_item_fn_mut(
927 gen_future_span,
928 hir::LangItem::GetContext,
929 self.arena.alloc_from_iter([task_context])arena_vec![self; task_context],
930 );
931 let call = match await_kind {
932 FutureKind::Future => self.expr_call_lang_item_fn(
933 span,
934 hir::LangItem::FuturePoll,
935 self.arena.alloc_from_iter([new_unchecked, get_context])arena_vec![self; new_unchecked, get_context],
936 ),
937 FutureKind::AsyncIterator => self.expr_call_lang_item_fn(
938 span,
939 hir::LangItem::AsyncIteratorPollNext,
940 self.arena.alloc_from_iter([new_unchecked, get_context])arena_vec![self; new_unchecked, get_context],
941 ),
942 };
943 self.arena.alloc(self.expr_unsafe(span, call))
944 };
945
946 let loop_node_id = self.next_node_id();
948 let loop_hir_id = self.lower_node_id(loop_node_id);
949 let ready_arm = {
950 let x_ident = Ident::with_dummy_span(sym::result);
951 let (x_pat, x_pat_hid) = self.pat_ident(gen_future_span, x_ident);
952 let x_expr = self.expr_ident(gen_future_span, x_ident, x_pat_hid);
953 let ready_field = self.single_pat_field(gen_future_span, x_pat);
954 let ready_pat = self.pat_lang_item_variant(span, hir::LangItem::PollReady, ready_field);
955 let break_x = self.with_loop_scope(loop_hir_id, move |this| {
956 let expr_break =
957 hir::ExprKind::Break(this.lower_loop_destination(None), Some(x_expr));
958 this.arena.alloc(this.expr(gen_future_span, expr_break))
959 });
960 self.arm(ready_pat, break_x, span)
961 };
962
963 let pending_arm = {
965 let pending_pat = self.pat_lang_item_variant(span, hir::LangItem::PollPending, &[]);
966 let empty_block = self.expr_block_empty(span);
967 self.arm(pending_pat, empty_block, span)
968 };
969
970 let inner_match_stmt = {
971 let match_expr = self.expr_match(
972 span,
973 poll_expr,
974 self.arena.alloc_from_iter([ready_arm, pending_arm])arena_vec![self; ready_arm, pending_arm],
975 hir::MatchSource::AwaitDesugar,
976 );
977 self.stmt_expr(span, match_expr)
978 };
979
980 let yield_stmt = {
984 let yielded = if is_async_gen {
985 self.arena.alloc(self.expr_lang_item_path(span, hir::LangItem::AsyncGenPending))
986 } else {
987 self.expr_unit(span)
988 };
989
990 let yield_expr = self.expr(
991 span,
992 hir::ExprKind::Yield(yielded, hir::YieldSource::Await { expr: Some(expr_hir_id) }),
993 );
994 let yield_expr = self.arena.alloc(yield_expr);
995
996 let Some(task_context_hid) = self.task_context else {
997 {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("use of `await` outside of an async context.")));
};unreachable!("use of `await` outside of an async context.");
998 };
999
1000 let lhs = self.expr_ident(span, task_context_ident, task_context_hid);
1001 let assign =
1002 self.expr(span, hir::ExprKind::Assign(lhs, yield_expr, self.lower_span(span)));
1003 self.stmt_expr(span, assign)
1004 };
1005
1006 let loop_block = self.block_all(span, self.arena.alloc_from_iter([inner_match_stmt, yield_stmt])arena_vec![self; inner_match_stmt, yield_stmt], None);
1007
1008 let loop_expr = self.arena.alloc(hir::Expr {
1010 hir_id: loop_hir_id,
1011 kind: hir::ExprKind::Loop(
1012 loop_block,
1013 None,
1014 hir::LoopSource::Loop,
1015 self.lower_span(span),
1016 ),
1017 span: self.lower_span(span),
1018 });
1019
1020 let awaitee_arm = self.arm(awaitee_pat, loop_expr, span);
1022
1023 let into_future_expr = match await_kind {
1025 FutureKind::Future => self.expr_call_lang_item_fn(
1026 span,
1027 hir::LangItem::IntoFutureIntoFuture,
1028 self.arena.alloc_from_iter([*expr])arena_vec![self; *expr],
1029 ),
1030 FutureKind::AsyncIterator => expr,
1033 };
1034
1035 hir::ExprKind::Match(
1039 into_future_expr,
1040 self.arena.alloc_from_iter([awaitee_arm])arena_vec![self; awaitee_arm],
1041 hir::MatchSource::AwaitDesugar,
1042 )
1043 }
1044
1045 fn lower_expr_use(&mut self, use_kw_span: Span, expr: &Expr) -> hir::ExprKind<'hir> {
1046 hir::ExprKind::Use(self.lower_expr(expr), self.lower_span(use_kw_span))
1047 }
1048
1049 fn lower_expr_closure(
1050 &mut self,
1051 attrs: &[rustc_hir::Attribute],
1052 binder: &ClosureBinder,
1053 capture_clause: CaptureBy,
1054 closure_id: NodeId,
1055 constness: Const,
1056 movability: Movability,
1057 decl: &FnDecl,
1058 body: &Expr,
1059 fn_decl_span: Span,
1060 fn_arg_span: Span,
1061 ) -> hir::ExprKind<'hir> {
1062 let closure_def_id = self.local_def_id(closure_id);
1063 let (binder_clause, generic_params) = self.lower_closure_binder(binder);
1064
1065 let (body_id, closure_kind) = self.with_new_scopes(fn_decl_span, move |this| {
1066 let mut coroutine_kind = {
'done:
{
for i in attrs {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(Coroutine(_)) => {
break 'done
Some(hir::CoroutineKind::Coroutine(Movability::Movable));
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(attrs, Coroutine(_) => hir::CoroutineKind::Coroutine(Movability::Movable));
1067
1068 let body_id = this.lower_fn_body(decl, None, |this| {
1070 this.coroutine_kind = coroutine_kind;
1071 let e = this.lower_expr_mut(body);
1072 coroutine_kind = this.coroutine_kind;
1073 e
1074 });
1075 let coroutine_option =
1076 this.closure_movability_for_fn(decl, fn_decl_span, coroutine_kind, movability);
1077 (body_id, coroutine_option)
1078 });
1079
1080 let bound_generic_params = self.lower_lifetime_binder(closure_id, generic_params);
1081 let fn_decl = self.lower_fn_decl(decl, closure_id, fn_decl_span, FnDeclKind::Closure, None);
1083
1084 let c = self.arena.alloc(hir::Closure {
1085 def_id: closure_def_id,
1086 binder: binder_clause,
1087 capture_clause: self.lower_capture_clause(capture_clause),
1088 bound_generic_params,
1089 fn_decl,
1090 body: body_id,
1091 fn_decl_span: self.lower_span(fn_decl_span),
1092 fn_arg_span: Some(self.lower_span(fn_arg_span)),
1093 kind: closure_kind,
1094 constness: self.lower_constness(constness),
1095 });
1096
1097 hir::ExprKind::Closure(c)
1098 }
1099
1100 fn closure_movability_for_fn(
1101 &mut self,
1102 decl: &FnDecl,
1103 fn_decl_span: Span,
1104 coroutine_kind: Option<hir::CoroutineKind>,
1105 movability: Movability,
1106 ) -> hir::ClosureKind {
1107 match coroutine_kind {
1108 Some(hir::CoroutineKind::Coroutine(_)) => {
1109 if decl.inputs.len() > 1 {
1110 self.dcx().emit_err(CoroutineTooManyParameters { fn_decl_span });
1111 }
1112 hir::ClosureKind::Coroutine(hir::CoroutineKind::Coroutine(movability))
1113 }
1114 Some(
1115 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _)
1116 | hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)
1117 | hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _),
1118 ) => {
1119 {
::core::panicking::panic_fmt(format_args!("non-`async`/`gen` closure body turned `async`/`gen` during lowering"));
};panic!("non-`async`/`gen` closure body turned `async`/`gen` during lowering");
1120 }
1121 None => {
1122 if movability == Movability::Static {
1123 self.dcx().emit_err(ClosureCannotBeStatic { fn_decl_span });
1124 }
1125 hir::ClosureKind::Closure
1126 }
1127 }
1128 }
1129
1130 fn lower_closure_binder<'c>(
1131 &mut self,
1132 binder: &'c ClosureBinder,
1133 ) -> (hir::ClosureBinder, &'c [GenericParam]) {
1134 let (binder, params) = match binder {
1135 ClosureBinder::NotPresent => (hir::ClosureBinder::Default, &[][..]),
1136 ClosureBinder::For { span, generic_params } => {
1137 let span = self.lower_span(*span);
1138 (hir::ClosureBinder::For { span }, &**generic_params)
1139 }
1140 };
1141
1142 (binder, params)
1143 }
1144
1145 fn lower_expr_coroutine_closure(
1146 &mut self,
1147 binder: &ClosureBinder,
1148 capture_clause: CaptureBy,
1149 closure_id: NodeId,
1150 closure_hir_id: HirId,
1151 coroutine_kind: CoroutineKind,
1152 constness: Const,
1153 decl: &FnDecl,
1154 body: &Expr,
1155 fn_decl_span: Span,
1156 fn_arg_span: Span,
1157 ) -> hir::ExprKind<'hir> {
1158 let closure_def_id = self.local_def_id(closure_id);
1159 let (binder_clause, generic_params) = self.lower_closure_binder(binder);
1160
1161 let coroutine_desugaring = match coroutine_kind {
1162 CoroutineKind::Async { .. } => hir::CoroutineDesugaring::Async,
1163 CoroutineKind::Gen { .. } => hir::CoroutineDesugaring::Gen,
1164 CoroutineKind::AsyncGen { span, .. } => {
1165 ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("only async closures and `iter!` closures are supported currently"))span_bug!(span, "only async closures and `iter!` closures are supported currently")
1166 }
1167 };
1168
1169 let body = self.with_new_scopes(fn_decl_span, |this| {
1170 let inner_decl =
1171 FnDecl { inputs: decl.inputs.clone(), output: FnRetTy::Default(fn_decl_span) };
1172
1173 let body_id = this.lower_body(|this| {
1176 let (parameters, expr) = this.lower_coroutine_body_with_moved_arguments(
1177 &inner_decl,
1178 |this| this.with_new_scopes(fn_decl_span, |this| this.lower_expr_mut(body)),
1179 fn_decl_span,
1180 body.span,
1181 coroutine_kind,
1182 hir::CoroutineSource::Closure,
1183 );
1184
1185 this.maybe_forward_track_caller(body.span, closure_hir_id, expr.hir_id);
1186
1187 (parameters, expr)
1188 });
1189 body_id
1190 });
1191
1192 let bound_generic_params = self.lower_lifetime_binder(closure_id, generic_params);
1193 let fn_decl =
1197 self.lower_fn_decl(&decl, closure_id, fn_decl_span, FnDeclKind::Closure, None);
1198
1199 if let Const::Yes(span) = constness {
1200 self.dcx().span_err(span, "const coroutines are not supported");
1201 }
1202
1203 let c = self.arena.alloc(hir::Closure {
1204 def_id: closure_def_id,
1205 binder: binder_clause,
1206 capture_clause: self.lower_capture_clause(capture_clause),
1207 bound_generic_params,
1208 fn_decl,
1209 body,
1210 fn_decl_span: self.lower_span(fn_decl_span),
1211 fn_arg_span: Some(self.lower_span(fn_arg_span)),
1212 kind: hir::ClosureKind::CoroutineClosure(coroutine_desugaring),
1216 constness: self.lower_constness(constness),
1217 });
1218 hir::ExprKind::Closure(c)
1219 }
1220
1221 fn lower_expr_assign(
1224 &mut self,
1225 lhs: &Expr,
1226 rhs: &Expr,
1227 eq_sign_span: Span,
1228 whole_span: Span,
1229 ) -> hir::ExprKind<'hir> {
1230 fn is_ordinary(lower_ctx: &mut LoweringContext<'_, '_>, lhs: &Expr) -> bool {
1232 match &lhs.kind {
1233 ExprKind::Array(..)
1234 | ExprKind::Struct(..)
1235 | ExprKind::Tup(..)
1236 | ExprKind::Underscore => false,
1237 ExprKind::Path(..) => lower_ctx.extract_unit_struct_path(lhs).is_none(),
1239 ExprKind::Call(callee, ..) => lower_ctx.extract_tuple_struct_path(callee).is_none(),
1241 ExprKind::Paren(e) => {
1242 match e.kind {
1243 ExprKind::Range(None, None, RangeLimits::HalfOpen) => false,
1245 _ => is_ordinary(lower_ctx, e),
1246 }
1247 }
1248 _ => true,
1249 }
1250 }
1251 if is_ordinary(self, lhs) {
1252 return hir::ExprKind::Assign(
1253 self.lower_expr(lhs),
1254 self.lower_expr(rhs),
1255 self.lower_span(eq_sign_span),
1256 );
1257 }
1258
1259 let mut assignments = ::alloc::vec::Vec::new()vec![];
1260
1261 let pat = self.destructure_assign(lhs, eq_sign_span, &mut assignments);
1263 let rhs = self.lower_expr(rhs);
1264
1265 let destructure_let =
1267 self.stmt_let_pat(None, whole_span, Some(rhs), pat, hir::LocalSource::AssignDesugar);
1268
1269 let stmts = self.arena.alloc_from_iter(std::iter::once(destructure_let).chain(assignments));
1271
1272 hir::ExprKind::Block(self.block_all(whole_span, stmts, None), None)
1274 }
1275
1276 fn extract_tuple_struct_path<'a>(
1281 &mut self,
1282 expr: &'a Expr,
1283 ) -> Option<(&'a Option<Box<QSelf>>, &'a Path)> {
1284 if let ExprKind::Path(qself, path) = &expr.kind {
1285 if let Some(partial_res) = self.get_partial_res(expr.id) {
1287 if let Some(res) = partial_res.full_res()
1288 && !res.expected_in_tuple_struct_pat()
1289 {
1290 return None;
1291 }
1292 }
1293 return Some((qself, path));
1294 }
1295 None
1296 }
1297
1298 fn extract_unit_struct_path<'a>(
1303 &mut self,
1304 expr: &'a Expr,
1305 ) -> Option<(&'a Option<Box<QSelf>>, &'a Path)> {
1306 if let ExprKind::Path(qself, path) = &expr.kind {
1307 if let Some(partial_res) = self.get_partial_res(expr.id) {
1309 if let Some(res) = partial_res.full_res()
1310 && !res.expected_in_unit_struct_pat()
1311 {
1312 return None;
1313 }
1314 }
1315 return Some((qself, path));
1316 }
1317 None
1318 }
1319
1320 fn destructure_assign(
1323 &mut self,
1324 lhs: &Expr,
1325 eq_sign_span: Span,
1326 assignments: &mut Vec<hir::Stmt<'hir>>,
1327 ) -> &'hir hir::Pat<'hir> {
1328 self.arena.alloc(self.destructure_assign_mut(lhs, eq_sign_span, assignments))
1329 }
1330
1331 fn destructure_assign_mut(
1332 &mut self,
1333 lhs: &Expr,
1334 eq_sign_span: Span,
1335 assignments: &mut Vec<hir::Stmt<'hir>>,
1336 ) -> hir::Pat<'hir> {
1337 match &lhs.kind {
1338 ExprKind::Underscore => {
1340 return self.pat_without_dbm(lhs.span, hir::PatKind::Wild);
1341 }
1342 ExprKind::Array(elements) => {
1344 let (pats, rest) =
1345 self.destructure_sequence(elements, "slice", eq_sign_span, assignments);
1346 let slice_pat = if let Some((i, span)) = rest {
1347 let (before, after) = pats.split_at(i);
1348 hir::PatKind::Slice(
1349 before,
1350 Some(self.arena.alloc(self.pat_without_dbm(span, hir::PatKind::Wild))),
1351 after,
1352 )
1353 } else {
1354 hir::PatKind::Slice(pats, None, &[])
1355 };
1356 return self.pat_without_dbm(lhs.span, slice_pat);
1357 }
1358 ExprKind::Call(callee, args) => {
1360 if let Some((qself, path)) = self.extract_tuple_struct_path(callee) {
1361 let (pats, rest) = self.destructure_sequence(
1362 args,
1363 "tuple struct or variant",
1364 eq_sign_span,
1365 assignments,
1366 );
1367 let qpath = self.lower_qpath(
1368 callee.id,
1369 qself,
1370 path,
1371 ParamMode::Optional,
1372 AllowReturnTypeNotation::No,
1373 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1374 None,
1375 );
1376 let tuple_struct_pat = hir::PatKind::TupleStruct(
1378 qpath,
1379 pats,
1380 hir::DotDotPos::new(rest.map(|r| r.0)),
1381 );
1382 return self.pat_without_dbm(lhs.span, tuple_struct_pat);
1383 }
1384 }
1385 ExprKind::Path(..) => {
1387 if let Some((qself, path)) = self.extract_unit_struct_path(lhs) {
1388 let qpath = self.lower_qpath(
1389 lhs.id,
1390 qself,
1391 path,
1392 ParamMode::Optional,
1393 AllowReturnTypeNotation::No,
1394 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1395 None,
1396 );
1397 let unit_struct_pat = hir::PatKind::Expr(self.arena.alloc(hir::PatExpr {
1399 kind: hir::PatExprKind::Path(qpath),
1400 hir_id: self.next_id(),
1401 span: self.lower_span(lhs.span),
1402 }));
1403 return self.pat_without_dbm(lhs.span, unit_struct_pat);
1404 }
1405 }
1406 ExprKind::Struct(se) => {
1408 let field_pats = self.arena.alloc_from_iter(se.fields.iter().map(|f| {
1409 let pat = self.destructure_assign(&f.expr, eq_sign_span, assignments);
1410 hir::PatField {
1411 hir_id: self.next_id(),
1412 ident: self.lower_ident(f.ident),
1413 pat,
1414 is_shorthand: f.is_shorthand,
1415 span: self.lower_span(f.span),
1416 }
1417 }));
1418 let qpath = self.lower_qpath(
1419 lhs.id,
1420 &se.qself,
1421 &se.path,
1422 ParamMode::Optional,
1423 AllowReturnTypeNotation::No,
1424 ImplTraitContext::Disallowed(ImplTraitPosition::Path),
1425 None,
1426 );
1427 let fields_omitted = match &se.rest {
1428 StructRest::Base(e) => {
1429 self.dcx().emit_err(FunctionalRecordUpdateDestructuringAssignment {
1430 span: e.span,
1431 });
1432 Some(self.lower_span(e.span))
1433 }
1434 StructRest::Rest(span) => Some(self.lower_span(*span)),
1435 StructRest::None | StructRest::NoneWithError(_) => None,
1436 };
1437 let struct_pat = hir::PatKind::Struct(qpath, field_pats, fields_omitted);
1438 return self.pat_without_dbm(lhs.span, struct_pat);
1439 }
1440 ExprKind::Tup(elements) => {
1442 let (pats, rest) =
1443 self.destructure_sequence(elements, "tuple", eq_sign_span, assignments);
1444 let tuple_pat = hir::PatKind::Tuple(pats, hir::DotDotPos::new(rest.map(|r| r.0)));
1445 return self.pat_without_dbm(lhs.span, tuple_pat);
1446 }
1447 ExprKind::Paren(e) => {
1448 if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
1450 let tuple_pat = hir::PatKind::Tuple(&[], hir::DotDotPos::new(Some(0)));
1451 return self.pat_without_dbm(lhs.span, tuple_pat);
1452 } else {
1453 return self.destructure_assign_mut(e, eq_sign_span, assignments);
1454 }
1455 }
1456 _ => {}
1457 }
1458 let ident = Ident::new(sym::lhs, self.lower_span(lhs.span));
1460 let (pat, binding) = self.pat_ident_mut(lhs.span, ident);
1461 let ident = self.expr_ident(lhs.span, ident, binding);
1462 let assign =
1463 hir::ExprKind::Assign(self.lower_expr(lhs), ident, self.lower_span(eq_sign_span));
1464 let expr = self.expr(lhs.span, assign);
1465 assignments.push(self.stmt_expr(lhs.span, expr));
1466 pat
1467 }
1468
1469 fn destructure_sequence(
1475 &mut self,
1476 elements: &[Box<Expr>],
1477 ctx: &str,
1478 eq_sign_span: Span,
1479 assignments: &mut Vec<hir::Stmt<'hir>>,
1480 ) -> (&'hir [hir::Pat<'hir>], Option<(usize, Span)>) {
1481 let mut rest = None;
1482 let elements =
1483 self.arena.alloc_from_iter(elements.iter().enumerate().filter_map(|(i, e)| {
1484 if let ExprKind::Range(None, None, RangeLimits::HalfOpen) = e.kind {
1486 if let Some((_, prev_span)) = rest {
1487 self.ban_extra_rest_pat(e.span, prev_span, ctx);
1488 } else {
1489 rest = Some((i, e.span));
1490 }
1491 None
1492 } else {
1493 Some(self.destructure_assign_mut(e, eq_sign_span, assignments))
1494 }
1495 }));
1496 (elements, rest)
1497 }
1498
1499 fn lower_expr_range_closed(&mut self, span: Span, e1: &Expr, e2: &Expr) -> hir::ExprKind<'hir> {
1501 let e1 = self.lower_expr_mut(e1);
1502 let e2 = self.lower_expr_mut(e2);
1503 let fn_path = self.make_lang_item_qpath(hir::LangItem::RangeInclusiveNew, span, None);
1504 let fn_expr = self.arena.alloc(self.expr(span, hir::ExprKind::Path(fn_path)));
1505 hir::ExprKind::Call(fn_expr, self.arena.alloc_from_iter([e1, e2])arena_vec![self; e1, e2])
1506 }
1507
1508 fn lower_expr_range(
1509 &mut self,
1510 span: Span,
1511 e1: Option<&Expr>,
1512 e2: Option<&Expr>,
1513 lims: RangeLimits,
1514 ) -> hir::ExprKind<'hir> {
1515 use rustc_ast::RangeLimits::*;
1516
1517 let lang_item = match (e1, e2, lims) {
1518 (None, None, HalfOpen) => hir::LangItem::RangeFull,
1519 (Some(..), None, HalfOpen) => {
1520 if self.tcx.features().new_range() {
1521 hir::LangItem::RangeFromCopy
1522 } else {
1523 hir::LangItem::RangeFrom
1524 }
1525 }
1526 (None, Some(..), HalfOpen) => hir::LangItem::RangeTo,
1527 (Some(..), Some(..), HalfOpen) => {
1528 if self.tcx.features().new_range() {
1529 hir::LangItem::RangeCopy
1530 } else {
1531 hir::LangItem::Range
1532 }
1533 }
1534 (None, Some(..), Closed) => {
1535 if self.tcx.features().new_range() {
1536 hir::LangItem::RangeToInclusiveCopy
1537 } else {
1538 hir::LangItem::RangeToInclusive
1539 }
1540 }
1541 (Some(e1), Some(e2), Closed) => {
1542 if self.tcx.features().new_range() {
1543 hir::LangItem::RangeInclusiveCopy
1544 } else {
1545 return self.lower_expr_range_closed(span, e1, e2);
1546 }
1547 }
1548 (start, None, Closed) => {
1549 self.dcx().emit_err(InclusiveRangeWithNoEnd { span });
1550 match start {
1551 Some(..) => {
1552 if self.tcx.features().new_range() {
1553 hir::LangItem::RangeFromCopy
1554 } else {
1555 hir::LangItem::RangeFrom
1556 }
1557 }
1558 None => hir::LangItem::RangeFull,
1559 }
1560 }
1561 };
1562
1563 let fields = self.arena.alloc_from_iter(
1564 e1.iter()
1565 .map(|e| (sym::start, e))
1566 .chain(e2.iter().map(|e| {
1567 (
1568 if #[allow(non_exhaustive_omitted_patterns)] match lang_item {
hir::LangItem::RangeInclusiveCopy | hir::LangItem::RangeToInclusiveCopy =>
true,
_ => false,
}matches!(
1569 lang_item,
1570 hir::LangItem::RangeInclusiveCopy | hir::LangItem::RangeToInclusiveCopy
1571 ) {
1572 sym::last
1573 } else {
1574 sym::end
1575 },
1576 e,
1577 )
1578 }))
1579 .map(|(s, e)| {
1580 let span = self.lower_span(e.span);
1581 let span = self.mark_span_with_reason(DesugaringKind::RangeExpr, span, None);
1582 let expr = self.lower_expr(e);
1583 let ident = Ident::new(s, span);
1584 self.expr_field(ident, expr, span)
1585 }),
1586 );
1587
1588 hir::ExprKind::Struct(
1589 self.arena.alloc(self.make_lang_item_qpath(lang_item, span, None)),
1590 fields,
1591 hir::StructTailExpr::None,
1592 )
1593 }
1594
1595 fn lower_label(
1598 &mut self,
1599 opt_label: Option<Label>,
1600 dest_id: NodeId,
1601 dest_hir_id: hir::HirId,
1602 ) -> Option<Label> {
1603 let label = opt_label?;
1604 self.ident_and_label_to_local_id.insert(dest_id, dest_hir_id.local_id);
1605 Some(Label { ident: self.lower_ident(label.ident) })
1606 }
1607
1608 fn lower_loop_destination(&mut self, destination: Option<(NodeId, Label)>) -> hir::Destination {
1609 let target_id = match destination {
1610 Some((id, _)) => {
1611 if let Some(loop_id) = self.resolver.get_label_res(id) {
1612 let local_id = self.ident_and_label_to_local_id[&loop_id];
1613 let loop_hir_id = HirId { owner: self.current_hir_id_owner, local_id };
1614 Ok(loop_hir_id)
1615 } else {
1616 Err(hir::LoopIdError::UnresolvedLabel)
1617 }
1618 }
1619 None => {
1620 self.loop_scope.map(|id| Ok(id)).unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
1621 }
1622 };
1623 let label = destination
1624 .map(|(_, label)| label)
1625 .map(|label| Label { ident: self.lower_ident(label.ident) });
1626 hir::Destination { label, target_id }
1627 }
1628
1629 fn lower_jump_destination(&mut self, id: NodeId, opt_label: Option<Label>) -> hir::Destination {
1630 if self.is_in_loop_condition && opt_label.is_none() {
1631 hir::Destination {
1632 label: None,
1633 target_id: Err(hir::LoopIdError::UnlabeledCfInWhileCondition),
1634 }
1635 } else {
1636 self.lower_loop_destination(opt_label.map(|label| (id, label)))
1637 }
1638 }
1639
1640 fn with_try_block_scope<T>(
1641 &mut self,
1642 scope: TryBlockScope,
1643 f: impl FnOnce(&mut Self) -> T,
1644 ) -> T {
1645 let old_scope = mem::replace(&mut self.try_block_scope, scope);
1646 let result = f(self);
1647 self.try_block_scope = old_scope;
1648 result
1649 }
1650
1651 fn with_loop_scope<T>(&mut self, loop_id: hir::HirId, f: impl FnOnce(&mut Self) -> T) -> T {
1652 let was_in_loop_condition = self.is_in_loop_condition;
1654 self.is_in_loop_condition = false;
1655
1656 let old_scope = self.loop_scope.replace(loop_id);
1657 let result = f(self);
1658 self.loop_scope = old_scope;
1659
1660 self.is_in_loop_condition = was_in_loop_condition;
1661
1662 result
1663 }
1664
1665 fn with_loop_condition_scope<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
1666 let was_in_loop_condition = self.is_in_loop_condition;
1667 self.is_in_loop_condition = true;
1668
1669 let result = f(self);
1670
1671 self.is_in_loop_condition = was_in_loop_condition;
1672
1673 result
1674 }
1675
1676 fn lower_expr_field(&mut self, f: &ExprField) -> hir::ExprField<'hir> {
1677 let hir_id = self.lower_node_id(f.id);
1678 self.lower_attrs(hir_id, &f.attrs, f.span, Target::ExprField);
1679 hir::ExprField {
1680 hir_id,
1681 ident: self.lower_ident(f.ident),
1682 expr: self.lower_expr(&f.expr),
1683 span: self.lower_span(f.span),
1684 is_shorthand: f.is_shorthand,
1685 }
1686 }
1687
1688 fn lower_expr_yield(&mut self, span: Span, opt_expr: Option<&Expr>) -> hir::ExprKind<'hir> {
1689 let yielded =
1690 opt_expr.as_ref().map(|x| self.lower_expr(x)).unwrap_or_else(|| self.expr_unit(span));
1691
1692 if !self.tcx.features().yield_expr()
1693 && !self.tcx.features().coroutines()
1694 && !self.tcx.features().gen_blocks()
1695 {
1696 rustc_session::errors::feature_err(
1697 &self.tcx.sess,
1698 sym::yield_expr,
1699 span,
1700 rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("yield syntax is experimental"))msg!("yield syntax is experimental"),
1701 )
1702 .emit();
1703 }
1704
1705 let is_async_gen = match self.coroutine_kind {
1706 Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _)) => false,
1707 Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _)) => true,
1708 Some(hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)) => {
1709 let stmt_id = self.next_id();
1712 let expr_err = self.expr(
1713 yielded.span,
1714 hir::ExprKind::Err(self.dcx().emit_err(AsyncCoroutinesNotSupported { span })),
1715 );
1716 return hir::ExprKind::Block(
1717 self.block_all(
1718 yielded.span,
1719 self.arena.alloc_from_iter([hir::Stmt {
hir_id: stmt_id,
kind: hir::StmtKind::Semi(yielded),
span: yielded.span,
}])arena_vec![self; hir::Stmt {
1720 hir_id: stmt_id,
1721 kind: hir::StmtKind::Semi(yielded),
1722 span: yielded.span,
1723 }],
1724 Some(self.arena.alloc(expr_err)),
1725 ),
1726 None,
1727 );
1728 }
1729 Some(hir::CoroutineKind::Coroutine(_)) => false,
1730 None => {
1731 let suggestion = self.current_item.map(|s| s.shrink_to_lo());
1732 self.dcx().emit_err(YieldInClosure { span, suggestion });
1733 self.coroutine_kind = Some(hir::CoroutineKind::Coroutine(Movability::Movable));
1734
1735 false
1736 }
1737 };
1738
1739 if is_async_gen {
1740 let desugar_span = self.mark_span_with_reason(
1744 DesugaringKind::Async,
1745 span,
1746 Some(Arc::clone(&self.allow_async_gen)),
1747 );
1748 let wrapped_yielded = self.expr_call_lang_item_fn(
1749 desugar_span,
1750 hir::LangItem::AsyncGenReady,
1751 std::slice::from_ref(yielded),
1752 );
1753 let yield_expr = self.arena.alloc(
1754 self.expr(span, hir::ExprKind::Yield(wrapped_yielded, hir::YieldSource::Yield)),
1755 );
1756
1757 let Some(task_context_hid) = self.task_context else {
1758 {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("use of `await` outside of an async context.")));
};unreachable!("use of `await` outside of an async context.");
1759 };
1760 let task_context_ident = Ident::with_dummy_span(sym::_task_context);
1761 let lhs = self.expr_ident(desugar_span, task_context_ident, task_context_hid);
1762
1763 hir::ExprKind::Assign(lhs, yield_expr, self.lower_span(span))
1764 } else {
1765 hir::ExprKind::Yield(yielded, hir::YieldSource::Yield)
1766 }
1767 }
1768
1769 fn lower_expr_for(
1786 &mut self,
1787 e: &Expr,
1788 pat: &Pat,
1789 head: &Expr,
1790 body: &Block,
1791 opt_label: Option<Label>,
1792 loop_kind: ForLoopKind,
1793 ) -> hir::Expr<'hir> {
1794 let head = self.lower_expr_mut(head);
1795 let pat = self.lower_pat(pat);
1796 let for_span =
1797 self.mark_span_with_reason(DesugaringKind::ForLoop, self.lower_span(e.span), None);
1798 let for_ctxt = for_span.ctxt();
1799
1800 let head_span =
1803 head.span.find_ancestor_in_same_ctxt(e.span).unwrap_or(head.span).with_ctxt(for_ctxt);
1804 let pat_span =
1805 pat.span.find_ancestor_in_same_ctxt(e.span).unwrap_or(pat.span).with_ctxt(for_ctxt);
1806
1807 let loop_hir_id = self.lower_node_id(e.id);
1808 let label = self.lower_label(opt_label, e.id, loop_hir_id);
1809
1810 let none_arm = {
1812 let break_expr =
1813 self.with_loop_scope(loop_hir_id, |this| this.expr_break_alloc(for_span));
1814 let pat = self.pat_none(for_span);
1815 self.arm(pat, break_expr, for_span)
1816 };
1817
1818 let some_arm = {
1820 let some_pat = self.pat_some(pat_span, pat);
1821 let body_block =
1822 self.with_loop_scope(loop_hir_id, |this| this.lower_block(body, false));
1823 let body_expr = self.arena.alloc(self.expr_block(body_block));
1824 self.arm(some_pat, body_expr, for_span)
1825 };
1826
1827 let iter = Ident::with_dummy_span(sym::iter);
1829 let (iter_pat, iter_pat_nid) =
1830 self.pat_ident_binding_mode(head_span, iter, hir::BindingMode::MUT);
1831
1832 let match_expr = {
1833 let iter = self.expr_ident(head_span, iter, iter_pat_nid);
1834 let next_expr = match loop_kind {
1835 ForLoopKind::For => {
1836 let ref_mut_iter = self.expr_mut_addr_of(head_span, iter);
1838 self.expr_call_lang_item_fn(
1839 head_span,
1840 hir::LangItem::IteratorNext,
1841 self.arena.alloc_from_iter([ref_mut_iter])arena_vec![self; ref_mut_iter],
1842 )
1843 }
1844 ForLoopKind::ForAwait => {
1845 let iter = self.expr_mut_addr_of(head_span, iter);
1852 let iter = self.arena.alloc(self.expr_call_lang_item_fn_mut(
1854 head_span,
1855 hir::LangItem::PinNewUnchecked,
1856 self.arena.alloc_from_iter([iter])arena_vec![self; iter],
1857 ));
1858 let iter = self.arena.alloc(self.expr_unsafe(head_span, iter));
1860 let kind = self.make_lowered_await(head_span, iter, FutureKind::AsyncIterator);
1861 self.arena.alloc(hir::Expr { hir_id: self.next_id(), kind, span: head_span })
1862 }
1863 };
1864 let arms = self.arena.alloc_from_iter([none_arm, some_arm])arena_vec![self; none_arm, some_arm];
1865
1866 self.expr_match(head_span, next_expr, arms, hir::MatchSource::ForLoopDesugar)
1868 };
1869 let match_stmt = self.stmt_expr(for_span, match_expr);
1870
1871 let loop_block = self.block_all(for_span, self.arena.alloc_from_iter([match_stmt])arena_vec![self; match_stmt], None);
1872
1873 let kind = hir::ExprKind::Loop(
1875 loop_block,
1876 label,
1877 hir::LoopSource::ForLoop,
1878 self.lower_span(for_span.with_hi(head.span.hi())),
1879 );
1880 let loop_expr = self.arena.alloc(hir::Expr { hir_id: loop_hir_id, kind, span: for_span });
1881
1882 let iter_arm = self.arm(iter_pat, loop_expr, for_span);
1884
1885 let match_expr = match loop_kind {
1886 ForLoopKind::For => {
1887 let into_iter_expr = self.expr_call_lang_item_fn(
1889 head_span,
1890 hir::LangItem::IntoIterIntoIter,
1891 self.arena.alloc_from_iter([head])arena_vec![self; head],
1892 );
1893
1894 self.arena.alloc(self.expr_match(
1895 for_span,
1896 into_iter_expr,
1897 self.arena.alloc_from_iter([iter_arm])arena_vec![self; iter_arm],
1898 hir::MatchSource::ForLoopDesugar,
1899 ))
1900 }
1901 ForLoopKind::ForAwait => {
1903 let iter_ident = iter;
1904 let (async_iter_pat, async_iter_pat_id) =
1905 self.pat_ident_binding_mode(head_span, iter_ident, hir::BindingMode::REF_MUT);
1906 let iter = self.expr_ident_mut(head_span, iter_ident, async_iter_pat_id);
1907 let iter = self.arena.alloc(self.expr_call_lang_item_fn_mut(
1909 head_span,
1910 hir::LangItem::PinNewUnchecked,
1911 self.arena.alloc_from_iter([iter])arena_vec![self; iter],
1912 ));
1913 let iter = self.arena.alloc(self.expr_unsafe(head_span, iter));
1915 let inner_match_expr = self.arena.alloc(self.expr_match(
1916 for_span,
1917 iter,
1918 self.arena.alloc_from_iter([iter_arm])arena_vec![self; iter_arm],
1919 hir::MatchSource::ForLoopDesugar,
1920 ));
1921
1922 let iter = self.expr_call_lang_item_fn(
1924 head_span,
1925 hir::LangItem::IntoAsyncIterIntoIter,
1926 self.arena.alloc_from_iter([head])arena_vec![self; head],
1927 );
1928 let iter_arm = self.arm(async_iter_pat, inner_match_expr, for_span);
1929 self.arena.alloc(self.expr_match(
1930 for_span,
1931 iter,
1932 self.arena.alloc_from_iter([iter_arm])arena_vec![self; iter_arm],
1933 hir::MatchSource::ForLoopDesugar,
1934 ))
1935 }
1936 };
1937
1938 let expr = self.expr_drop_temps_mut(for_span, match_expr);
1945 self.lower_attrs(expr.hir_id, &e.attrs, e.span, Target::from_expr(e));
1946 expr
1947 }
1948
1949 fn lower_expr_try(&mut self, span: Span, sub_expr: &Expr) -> hir::ExprKind<'hir> {
1962 let unstable_span = self.mark_span_with_reason(
1963 DesugaringKind::QuestionMark,
1964 span,
1965 Some(Arc::clone(&self.allow_try_trait)),
1966 );
1967 let try_span = self.tcx.sess.source_map().end_point(span);
1968 let try_span = self.mark_span_with_reason(
1969 DesugaringKind::QuestionMark,
1970 try_span,
1971 Some(Arc::clone(&self.allow_try_trait)),
1972 );
1973
1974 let scrutinee = {
1976 let sub_expr = self.lower_expr_mut(sub_expr);
1978
1979 self.expr_call_lang_item_fn(
1980 unstable_span,
1981 hir::LangItem::TryTraitBranch,
1982 self.arena.alloc_from_iter([sub_expr])arena_vec![self; sub_expr],
1983 )
1984 };
1985
1986 let attrs: AttrVec = {
let len = [()].len();
let mut vec = ::thin_vec::ThinVec::with_capacity(len);
vec.push(self.unreachable_code_attr(try_span));
vec
}thin_vec![self.unreachable_code_attr(try_span)];
1987
1988 let continue_arm = {
1990 let val_ident = Ident::with_dummy_span(sym::val);
1991 let (val_pat, val_pat_nid) = self.pat_ident(span, val_ident);
1992 let val_expr = self.expr_ident(span, val_ident, val_pat_nid);
1993 self.lower_attrs(val_expr.hir_id, &attrs, span, Target::Expression);
1994 let continue_pat = self.pat_cf_continue(unstable_span, val_pat);
1995 self.arm(continue_pat, val_expr, try_span)
1996 };
1997
1998 let break_arm = {
2002 let residual_ident = Ident::with_dummy_span(sym::residual);
2003 let (residual_local, residual_local_nid) = self.pat_ident(try_span, residual_ident);
2004 let residual_expr = self.expr_ident_mut(try_span, residual_ident, residual_local_nid);
2005
2006 let (constructor_item, target_id) = match self.try_block_scope {
2007 TryBlockScope::Function => {
2008 (hir::LangItem::TryTraitFromResidual, Err(hir::LoopIdError::OutsideLoopScope))
2009 }
2010 TryBlockScope::Homogeneous(block_id) => {
2011 (hir::LangItem::ResidualIntoTryType, Ok(block_id))
2012 }
2013 TryBlockScope::Heterogeneous(block_id) => {
2014 (hir::LangItem::TryTraitFromResidual, Ok(block_id))
2015 }
2016 };
2017 let from_residual_expr = self.wrap_in_try_constructor(
2018 constructor_item,
2019 try_span,
2020 self.arena.alloc(residual_expr),
2021 unstable_span,
2022 );
2023 let ret_expr = if target_id.is_ok() {
2024 self.arena.alloc(self.expr(
2025 try_span,
2026 hir::ExprKind::Break(
2027 hir::Destination { label: None, target_id },
2028 Some(from_residual_expr),
2029 ),
2030 ))
2031 } else {
2032 let ret_expr = self.checked_return(Some(from_residual_expr));
2033 self.arena.alloc(self.expr(try_span, ret_expr))
2034 };
2035 self.lower_attrs(ret_expr.hir_id, &attrs, span, Target::Expression);
2036
2037 let break_pat = self.pat_cf_break(try_span, residual_local);
2038 self.arm(break_pat, ret_expr, try_span)
2039 };
2040
2041 hir::ExprKind::Match(
2042 scrutinee,
2043 self.arena.alloc_from_iter([break_arm, continue_arm])arena_vec![self; break_arm, continue_arm],
2044 hir::MatchSource::TryDesugar(scrutinee.hir_id),
2045 )
2046 }
2047
2048 fn lower_expr_yeet(&mut self, span: Span, sub_expr: Option<&Expr>) -> hir::ExprKind<'hir> {
2058 let (yeeted_span, yeeted_expr) = if let Some(sub_expr) = sub_expr {
2060 (sub_expr.span, self.lower_expr(sub_expr))
2061 } else {
2062 (self.mark_span_with_reason(DesugaringKind::YeetExpr, span, None), self.expr_unit(span))
2063 };
2064
2065 let unstable_span = self.mark_span_with_reason(
2066 DesugaringKind::YeetExpr,
2067 span,
2068 Some(Arc::clone(&self.allow_try_trait)),
2069 );
2070
2071 let from_yeet_expr = self.wrap_in_try_constructor(
2072 hir::LangItem::TryTraitFromYeet,
2073 unstable_span,
2074 yeeted_expr,
2075 yeeted_span,
2076 );
2077
2078 match self.try_block_scope {
2079 TryBlockScope::Homogeneous(block_id) | TryBlockScope::Heterogeneous(block_id) => {
2080 hir::ExprKind::Break(
2081 hir::Destination { label: None, target_id: Ok(block_id) },
2082 Some(from_yeet_expr),
2083 )
2084 }
2085 TryBlockScope::Function => self.checked_return(Some(from_yeet_expr)),
2086 }
2087 }
2088
2089 pub(super) fn expr_drop_temps(
2101 &mut self,
2102 span: Span,
2103 expr: &'hir hir::Expr<'hir>,
2104 ) -> &'hir hir::Expr<'hir> {
2105 self.arena.alloc(self.expr_drop_temps_mut(span, expr))
2106 }
2107
2108 pub(super) fn expr_drop_temps_mut(
2109 &mut self,
2110 span: Span,
2111 expr: &'hir hir::Expr<'hir>,
2112 ) -> hir::Expr<'hir> {
2113 self.expr(span, hir::ExprKind::DropTemps(expr))
2114 }
2115
2116 pub(super) fn expr_match(
2117 &mut self,
2118 span: Span,
2119 arg: &'hir hir::Expr<'hir>,
2120 arms: &'hir [hir::Arm<'hir>],
2121 source: hir::MatchSource,
2122 ) -> hir::Expr<'hir> {
2123 self.expr(span, hir::ExprKind::Match(arg, arms, source))
2124 }
2125
2126 fn expr_break(&mut self, span: Span) -> hir::Expr<'hir> {
2127 let expr_break = hir::ExprKind::Break(self.lower_loop_destination(None), None);
2128 self.expr(span, expr_break)
2129 }
2130
2131 fn expr_break_alloc(&mut self, span: Span) -> &'hir hir::Expr<'hir> {
2132 let expr_break = self.expr_break(span);
2133 self.arena.alloc(expr_break)
2134 }
2135
2136 fn expr_mut_addr_of(&mut self, span: Span, e: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
2137 self.expr(span, hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Mut, e))
2138 }
2139
2140 pub(super) fn expr_unit(&mut self, sp: Span) -> &'hir hir::Expr<'hir> {
2141 self.arena.alloc(self.expr(sp, hir::ExprKind::Tup(&[])))
2142 }
2143
2144 pub(super) fn expr_str(&mut self, sp: Span, value: Symbol) -> hir::Expr<'hir> {
2145 let lit = hir::Lit {
2146 span: self.lower_span(sp),
2147 node: ast::LitKind::Str(value, ast::StrStyle::Cooked),
2148 };
2149 self.expr(sp, hir::ExprKind::Lit(lit))
2150 }
2151
2152 pub(super) fn expr_byte_str(&mut self, sp: Span, value: ByteSymbol) -> hir::Expr<'hir> {
2153 let lit = hir::Lit {
2154 span: self.lower_span(sp),
2155 node: ast::LitKind::ByteStr(value, ast::StrStyle::Cooked),
2156 };
2157 self.expr(sp, hir::ExprKind::Lit(lit))
2158 }
2159
2160 pub(super) fn expr_call_mut(
2161 &mut self,
2162 span: Span,
2163 e: &'hir hir::Expr<'hir>,
2164 args: &'hir [hir::Expr<'hir>],
2165 ) -> hir::Expr<'hir> {
2166 self.expr(span, hir::ExprKind::Call(e, args))
2167 }
2168
2169 pub(super) fn expr_struct(
2170 &mut self,
2171 span: Span,
2172 path: &'hir hir::QPath<'hir>,
2173 fields: &'hir [hir::ExprField<'hir>],
2174 ) -> hir::Expr<'hir> {
2175 self.expr(span, hir::ExprKind::Struct(path, fields, rustc_hir::StructTailExpr::None))
2176 }
2177
2178 pub(super) fn expr_enum_variant(
2179 &mut self,
2180 span: Span,
2181 path: &'hir hir::QPath<'hir>,
2182 fields: &'hir [hir::Expr<'hir>],
2183 ) -> hir::Expr<'hir> {
2184 let fields = self.arena.alloc_from_iter(fields.into_iter().enumerate().map(|(i, f)| {
2185 hir::ExprField {
2186 hir_id: self.next_id(),
2187 ident: Ident::from_str(&i.to_string()),
2188 expr: f,
2189 span: f.span,
2190 is_shorthand: false,
2191 }
2192 }));
2193 self.expr_struct(span, path, fields)
2194 }
2195
2196 pub(super) fn expr_enum_variant_lang_item(
2197 &mut self,
2198 span: Span,
2199 lang_item: hir::LangItem,
2200 fields: &'hir [hir::Expr<'hir>],
2201 ) -> hir::Expr<'hir> {
2202 let path = self.arena.alloc(self.make_lang_item_qpath(lang_item, span, None));
2203 self.expr_enum_variant(span, path, fields)
2204 }
2205
2206 pub(super) fn expr_call(
2207 &mut self,
2208 span: Span,
2209 e: &'hir hir::Expr<'hir>,
2210 args: &'hir [hir::Expr<'hir>],
2211 ) -> &'hir hir::Expr<'hir> {
2212 self.arena.alloc(self.expr_call_mut(span, e, args))
2213 }
2214
2215 pub(super) fn expr_call_lang_item_fn_mut(
2216 &mut self,
2217 span: Span,
2218 lang_item: hir::LangItem,
2219 args: &'hir [hir::Expr<'hir>],
2220 ) -> hir::Expr<'hir> {
2221 let path = self.arena.alloc(self.expr_lang_item_path(span, lang_item));
2222 self.expr_call_mut(span, path, args)
2223 }
2224
2225 pub(super) fn expr_call_lang_item_fn(
2226 &mut self,
2227 span: Span,
2228 lang_item: hir::LangItem,
2229 args: &'hir [hir::Expr<'hir>],
2230 ) -> &'hir hir::Expr<'hir> {
2231 self.arena.alloc(self.expr_call_lang_item_fn_mut(span, lang_item, args))
2232 }
2233
2234 pub(super) fn expr_lang_item_path(
2235 &mut self,
2236 span: Span,
2237 lang_item: hir::LangItem,
2238 ) -> hir::Expr<'hir> {
2239 let qpath = self.make_lang_item_qpath(lang_item, self.lower_span(span), None);
2240 self.expr(span, hir::ExprKind::Path(qpath))
2241 }
2242
2243 pub(super) fn expr_lang_item_type_relative(
2245 &mut self,
2246 span: Span,
2247 lang_item: hir::LangItem,
2248 name: Symbol,
2249 ) -> hir::Expr<'hir> {
2250 let qpath = self.make_lang_item_qpath(lang_item, self.lower_span(span), None);
2251 let path = hir::ExprKind::Path(hir::QPath::TypeRelative(
2252 self.arena.alloc(self.ty(span, hir::TyKind::Path(qpath))),
2253 self.arena.alloc(hir::PathSegment::new(
2254 Ident::new(name, self.lower_span(span)),
2255 self.next_id(),
2256 Res::Err,
2257 )),
2258 ));
2259 self.expr(span, path)
2260 }
2261
2262 pub(super) fn expr_ident(
2263 &mut self,
2264 sp: Span,
2265 ident: Ident,
2266 binding: HirId,
2267 ) -> &'hir hir::Expr<'hir> {
2268 self.arena.alloc(self.expr_ident_mut(sp, ident, binding))
2269 }
2270
2271 pub(super) fn expr_ident_mut(
2272 &mut self,
2273 span: Span,
2274 ident: Ident,
2275 binding: HirId,
2276 ) -> hir::Expr<'hir> {
2277 let hir_id = self.next_id();
2278 let res = Res::Local(binding);
2279 let expr_path = hir::ExprKind::Path(hir::QPath::Resolved(
2280 None,
2281 self.arena.alloc(hir::Path {
2282 span: self.lower_span(span),
2283 res,
2284 segments: self.arena.alloc_from_iter([hir::PathSegment::new(self.lower_ident(ident),
hir_id, res)])arena_vec![self; hir::PathSegment::new(self.lower_ident(ident), hir_id, res)],
2285 }),
2286 ));
2287
2288 self.expr(span, expr_path)
2289 }
2290
2291 pub(super) fn expr_unsafe(
2292 &mut self,
2293 span: Span,
2294 expr: &'hir hir::Expr<'hir>,
2295 ) -> hir::Expr<'hir> {
2296 let hir_id = self.next_id();
2297 self.expr(
2298 span,
2299 hir::ExprKind::Block(
2300 self.arena.alloc(hir::Block {
2301 stmts: &[],
2302 expr: Some(expr),
2303 hir_id,
2304 rules: hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::CompilerGenerated),
2305 span: self.lower_span(span),
2306 targeted_by_break: false,
2307 }),
2308 None,
2309 ),
2310 )
2311 }
2312
2313 fn expr_block_empty(&mut self, span: Span) -> &'hir hir::Expr<'hir> {
2314 let blk = self.block_all(span, &[], None);
2315 let expr = self.expr_block(blk);
2316 self.arena.alloc(expr)
2317 }
2318
2319 pub(super) fn expr_block(&mut self, b: &'hir hir::Block<'hir>) -> hir::Expr<'hir> {
2320 self.expr(b.span, hir::ExprKind::Block(b, None))
2321 }
2322
2323 pub(super) fn block_expr_block(
2327 &mut self,
2328 expr: &'hir hir::Expr<'hir>,
2329 ) -> &'hir hir::Expr<'hir> {
2330 let b = self.block_expr(expr);
2331 self.arena.alloc(self.expr_block(b))
2332 }
2333
2334 pub(super) fn expr_ref(&mut self, span: Span, expr: &'hir hir::Expr<'hir>) -> hir::Expr<'hir> {
2335 self.expr(span, hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, expr))
2336 }
2337
2338 pub(super) fn expr_bool_literal(&mut self, span: Span, val: bool) -> hir::Expr<'hir> {
2339 self.expr(span, hir::ExprKind::Lit(Spanned { node: LitKind::Bool(val), span }))
2340 }
2341
2342 pub(super) fn expr(&mut self, span: Span, kind: hir::ExprKind<'hir>) -> hir::Expr<'hir> {
2343 let hir_id = self.next_id();
2344 hir::Expr { hir_id, kind, span: self.lower_span(span) }
2345 }
2346
2347 pub(super) fn expr_field(
2348 &mut self,
2349 ident: Ident,
2350 expr: &'hir hir::Expr<'hir>,
2351 span: Span,
2352 ) -> hir::ExprField<'hir> {
2353 hir::ExprField {
2354 hir_id: self.next_id(),
2355 ident,
2356 span: self.lower_span(span),
2357 expr,
2358 is_shorthand: false,
2359 }
2360 }
2361
2362 pub(super) fn arm(
2363 &mut self,
2364 pat: &'hir hir::Pat<'hir>,
2365 expr: &'hir hir::Expr<'hir>,
2366 span: Span,
2367 ) -> hir::Arm<'hir> {
2368 hir::Arm {
2369 hir_id: self.next_id(),
2370 pat,
2371 guard: None,
2372 span: self.lower_span(span),
2373 body: expr,
2374 }
2375 }
2376
2377 pub(super) fn unreachable_code_attr(&mut self, span: Span) -> Attribute {
2379 let attr = attr::mk_attr_nested_word(
2380 &self.tcx.sess.psess.attr_id_generator,
2381 AttrStyle::Outer,
2382 Safety::Default,
2383 sym::allow,
2384 sym::unreachable_code,
2385 span,
2386 );
2387 attr
2388 }
2389}
2390
2391#[derive(#[automatically_derived]
impl ::core::marker::Copy for FutureKind { }Copy, #[automatically_derived]
impl ::core::clone::Clone for FutureKind {
#[inline]
fn clone(&self) -> FutureKind { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for FutureKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
FutureKind::Future => "Future",
FutureKind::AsyncIterator => "AsyncIterator",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for FutureKind {
#[inline]
fn eq(&self, other: &FutureKind) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for FutureKind {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq)]
2394enum FutureKind {
2395 Future,
2397 AsyncIterator,
2400}