]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast_lowering/src/item.rs
Rollup merge of #101573 - lcnr:param-kind-ord, r=BoxyUwU
[rust.git] / compiler / rustc_ast_lowering / src / item.rs
1 use super::errors::{InvalidAbi, MisplacedRelaxTraitBound};
2 use super::ResolverAstLoweringExt;
3 use super::{Arena, AstOwner, ImplTraitContext, ImplTraitPosition};
4 use super::{FnDeclKind, LoweringContext, ParamMode};
5
6 use rustc_ast::ptr::P;
7 use rustc_ast::visit::AssocCtxt;
8 use rustc_ast::*;
9 use rustc_data_structures::fx::FxHashMap;
10 use rustc_data_structures::sorted_map::SortedMap;
11 use rustc_hir as hir;
12 use rustc_hir::def::{DefKind, Res};
13 use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID};
14 use rustc_hir::PredicateOrigin;
15 use rustc_index::vec::{Idx, IndexVec};
16 use rustc_middle::ty::{DefIdTree, ResolverAstLowering, TyCtxt};
17 use rustc_span::source_map::DesugaringKind;
18 use rustc_span::symbol::{kw, sym, Ident};
19 use rustc_span::Span;
20 use rustc_target::spec::abi;
21 use smallvec::{smallvec, SmallVec};
22
23 use std::iter;
24
25 pub(super) struct ItemLowerer<'a, 'hir> {
26     pub(super) tcx: TyCtxt<'hir>,
27     pub(super) resolver: &'a mut ResolverAstLowering,
28     pub(super) ast_arena: &'a Arena<'static>,
29     pub(super) ast_index: &'a IndexVec<LocalDefId, AstOwner<'a>>,
30     pub(super) owners: &'a mut IndexVec<LocalDefId, hir::MaybeOwner<&'hir hir::OwnerInfo<'hir>>>,
31 }
32
33 /// When we have a ty alias we *may* have two where clauses. To give the best diagnostics, we set the span
34 /// to the where clause that is preferred, if it exists. Otherwise, it sets the span to the other where
35 /// clause if it exists.
36 fn add_ty_alias_where_clause(
37     generics: &mut ast::Generics,
38     mut where_clauses: (TyAliasWhereClause, TyAliasWhereClause),
39     prefer_first: bool,
40 ) {
41     if !prefer_first {
42         where_clauses = (where_clauses.1, where_clauses.0);
43     }
44     if where_clauses.0.0 || !where_clauses.1.0 {
45         generics.where_clause.has_where_token = where_clauses.0.0;
46         generics.where_clause.span = where_clauses.0.1;
47     } else {
48         generics.where_clause.has_where_token = where_clauses.1.0;
49         generics.where_clause.span = where_clauses.1.1;
50     }
51 }
52
53 impl<'a, 'hir> ItemLowerer<'a, 'hir> {
54     fn with_lctx(
55         &mut self,
56         owner: NodeId,
57         f: impl FnOnce(&mut LoweringContext<'_, 'hir>) -> hir::OwnerNode<'hir>,
58     ) {
59         let mut lctx = LoweringContext {
60             // Pseudo-globals.
61             tcx: self.tcx,
62             resolver: self.resolver,
63             arena: self.tcx.hir_arena,
64             ast_arena: self.ast_arena,
65
66             // HirId handling.
67             bodies: Vec::new(),
68             attrs: SortedMap::default(),
69             children: FxHashMap::default(),
70             current_hir_id_owner: CRATE_DEF_ID,
71             item_local_id_counter: hir::ItemLocalId::new(0),
72             node_id_to_local_id: Default::default(),
73             local_id_to_def_id: SortedMap::new(),
74             trait_map: Default::default(),
75
76             // Lowering state.
77             catch_scope: None,
78             loop_scope: None,
79             is_in_loop_condition: false,
80             is_in_trait_impl: false,
81             is_in_dyn_type: false,
82             generator_kind: None,
83             task_context: None,
84             current_item: None,
85             impl_trait_defs: Vec::new(),
86             impl_trait_bounds: Vec::new(),
87             allow_try_trait: Some([sym::try_trait_v2, sym::yeet_desugar_details][..].into()),
88             allow_gen_future: Some([sym::gen_future][..].into()),
89             allow_into_future: Some([sym::into_future][..].into()),
90             generics_def_id_map: Default::default(),
91         };
92         lctx.with_hir_id_owner(owner, |lctx| f(lctx));
93
94         for (def_id, info) in lctx.children {
95             self.owners.ensure_contains_elem(def_id, || hir::MaybeOwner::Phantom);
96             debug_assert!(matches!(self.owners[def_id], hir::MaybeOwner::Phantom));
97             self.owners[def_id] = info;
98         }
99     }
100
101     pub(super) fn lower_node(
102         &mut self,
103         def_id: LocalDefId,
104     ) -> hir::MaybeOwner<&'hir hir::OwnerInfo<'hir>> {
105         self.owners.ensure_contains_elem(def_id, || hir::MaybeOwner::Phantom);
106         if let hir::MaybeOwner::Phantom = self.owners[def_id] {
107             let node = self.ast_index[def_id];
108             match node {
109                 AstOwner::NonOwner => {}
110                 AstOwner::Crate(c) => self.lower_crate(c),
111                 AstOwner::Item(item) => self.lower_item(item),
112                 AstOwner::AssocItem(item, ctxt) => self.lower_assoc_item(item, ctxt),
113                 AstOwner::ForeignItem(item) => self.lower_foreign_item(item),
114             }
115         }
116
117         self.owners[def_id]
118     }
119
120     #[instrument(level = "debug", skip(self, c))]
121     fn lower_crate(&mut self, c: &Crate) {
122         debug_assert_eq!(self.resolver.node_id_to_def_id[&CRATE_NODE_ID], CRATE_DEF_ID);
123         self.with_lctx(CRATE_NODE_ID, |lctx| {
124             let module = lctx.lower_mod(&c.items, &c.spans);
125             lctx.lower_attrs(hir::CRATE_HIR_ID, &c.attrs);
126             hir::OwnerNode::Crate(module)
127         })
128     }
129
130     #[instrument(level = "debug", skip(self))]
131     fn lower_item(&mut self, item: &Item) {
132         self.with_lctx(item.id, |lctx| hir::OwnerNode::Item(lctx.lower_item(item)))
133     }
134
135     fn lower_assoc_item(&mut self, item: &AssocItem, ctxt: AssocCtxt) {
136         let def_id = self.resolver.node_id_to_def_id[&item.id];
137
138         let parent_id = self.tcx.local_parent(def_id);
139         let parent_hir = self.lower_node(parent_id).unwrap();
140         self.with_lctx(item.id, |lctx| {
141             // Evaluate with the lifetimes in `params` in-scope.
142             // This is used to track which lifetimes have already been defined,
143             // and which need to be replicated when lowering an async fn.
144             match parent_hir.node().expect_item().kind {
145                 hir::ItemKind::Impl(hir::Impl { ref of_trait, .. }) => {
146                     lctx.is_in_trait_impl = of_trait.is_some();
147                 }
148                 _ => {}
149             };
150
151             match ctxt {
152                 AssocCtxt::Trait => hir::OwnerNode::TraitItem(lctx.lower_trait_item(item)),
153                 AssocCtxt::Impl => hir::OwnerNode::ImplItem(lctx.lower_impl_item(item)),
154             }
155         })
156     }
157
158     fn lower_foreign_item(&mut self, item: &ForeignItem) {
159         self.with_lctx(item.id, |lctx| hir::OwnerNode::ForeignItem(lctx.lower_foreign_item(item)))
160     }
161 }
162
163 impl<'hir> LoweringContext<'_, 'hir> {
164     pub(super) fn lower_mod(
165         &mut self,
166         items: &[P<Item>],
167         spans: &ModSpans,
168     ) -> &'hir hir::Mod<'hir> {
169         self.arena.alloc(hir::Mod {
170             spans: hir::ModSpans {
171                 inner_span: self.lower_span(spans.inner_span),
172                 inject_use_span: self.lower_span(spans.inject_use_span),
173             },
174             item_ids: self.arena.alloc_from_iter(items.iter().flat_map(|x| self.lower_item_ref(x))),
175         })
176     }
177
178     pub(super) fn lower_item_ref(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
179         let mut node_ids = smallvec![hir::ItemId { def_id: self.local_def_id(i.id) }];
180         if let ItemKind::Use(ref use_tree) = &i.kind {
181             self.lower_item_id_use_tree(use_tree, i.id, &mut node_ids);
182         }
183         node_ids
184     }
185
186     fn lower_item_id_use_tree(
187         &mut self,
188         tree: &UseTree,
189         base_id: NodeId,
190         vec: &mut SmallVec<[hir::ItemId; 1]>,
191     ) {
192         match tree.kind {
193             UseTreeKind::Nested(ref nested_vec) => {
194                 for &(ref nested, id) in nested_vec {
195                     vec.push(hir::ItemId { def_id: self.local_def_id(id) });
196                     self.lower_item_id_use_tree(nested, id, vec);
197                 }
198             }
199             UseTreeKind::Glob => {}
200             UseTreeKind::Simple(_, id1, id2) => {
201                 for (_, &id) in
202                     iter::zip(self.expect_full_res_from_use(base_id).skip(1), &[id1, id2])
203                 {
204                     vec.push(hir::ItemId { def_id: self.local_def_id(id) });
205                 }
206             }
207         }
208     }
209
210     fn lower_item(&mut self, i: &Item) -> &'hir hir::Item<'hir> {
211         let mut ident = i.ident;
212         let vis_span = self.lower_span(i.vis.span);
213         let hir_id = self.lower_node_id(i.id);
214         let attrs = self.lower_attrs(hir_id, &i.attrs);
215         let kind = self.lower_item_kind(i.span, i.id, hir_id, &mut ident, attrs, vis_span, &i.kind);
216         let item = hir::Item {
217             def_id: hir_id.expect_owner(),
218             ident: self.lower_ident(ident),
219             kind,
220             vis_span,
221             span: self.lower_span(i.span),
222         };
223         self.arena.alloc(item)
224     }
225
226     fn lower_item_kind(
227         &mut self,
228         span: Span,
229         id: NodeId,
230         hir_id: hir::HirId,
231         ident: &mut Ident,
232         attrs: Option<&'hir [Attribute]>,
233         vis_span: Span,
234         i: &ItemKind,
235     ) -> hir::ItemKind<'hir> {
236         match *i {
237             ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name),
238             ItemKind::Use(ref use_tree) => {
239                 // Start with an empty prefix.
240                 let prefix = Path { segments: vec![], span: use_tree.span, tokens: None };
241
242                 self.lower_use_tree(use_tree, &prefix, id, vis_span, ident, attrs)
243             }
244             ItemKind::Static(ref t, m, ref e) => {
245                 let (ty, body_id) = self.lower_const_item(t, span, e.as_deref());
246                 hir::ItemKind::Static(ty, m, body_id)
247             }
248             ItemKind::Const(_, ref t, ref e) => {
249                 let (ty, body_id) = self.lower_const_item(t, span, e.as_deref());
250                 hir::ItemKind::Const(ty, body_id)
251             }
252             ItemKind::Fn(box Fn {
253                 sig: FnSig { ref decl, header, span: fn_sig_span },
254                 ref generics,
255                 ref body,
256                 ..
257             }) => {
258                 self.with_new_scopes(|this| {
259                     this.current_item = Some(ident.span);
260
261                     // Note: we don't need to change the return type from `T` to
262                     // `impl Future<Output = T>` here because lower_body
263                     // only cares about the input argument patterns in the function
264                     // declaration (decl), not the return types.
265                     let asyncness = header.asyncness;
266                     let body_id =
267                         this.lower_maybe_async_body(span, &decl, asyncness, body.as_deref());
268
269                     let mut itctx = ImplTraitContext::Universal;
270                     let (generics, decl) = this.lower_generics(generics, id, &mut itctx, |this| {
271                         let ret_id = asyncness.opt_return_id();
272                         this.lower_fn_decl(&decl, Some(id), fn_sig_span, FnDeclKind::Fn, ret_id)
273                     });
274                     let sig = hir::FnSig {
275                         decl,
276                         header: this.lower_fn_header(header),
277                         span: this.lower_span(fn_sig_span),
278                     };
279                     hir::ItemKind::Fn(sig, generics, body_id)
280                 })
281             }
282             ItemKind::Mod(_, ref mod_kind) => match mod_kind {
283                 ModKind::Loaded(items, _, spans) => {
284                     hir::ItemKind::Mod(self.lower_mod(items, spans))
285                 }
286                 ModKind::Unloaded => panic!("`mod` items should have been loaded by now"),
287             },
288             ItemKind::ForeignMod(ref fm) => hir::ItemKind::ForeignMod {
289                 abi: fm.abi.map_or(abi::Abi::FALLBACK, |abi| self.lower_abi(abi)),
290                 items: self
291                     .arena
292                     .alloc_from_iter(fm.items.iter().map(|x| self.lower_foreign_item_ref(x))),
293             },
294             ItemKind::GlobalAsm(ref asm) => {
295                 hir::ItemKind::GlobalAsm(self.lower_inline_asm(span, asm))
296             }
297             ItemKind::TyAlias(box TyAlias {
298                 ref generics,
299                 where_clauses,
300                 ty: Some(ref ty),
301                 ..
302             }) => {
303                 // We lower
304                 //
305                 // type Foo = impl Trait
306                 //
307                 // to
308                 //
309                 // type Foo = Foo1
310                 // opaque type Foo1: Trait
311                 let mut generics = generics.clone();
312                 add_ty_alias_where_clause(&mut generics, where_clauses, true);
313                 let (generics, ty) = self.lower_generics(
314                     &generics,
315                     id,
316                     &mut ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
317                     |this| this.lower_ty(ty, &mut ImplTraitContext::TypeAliasesOpaqueTy),
318                 );
319                 hir::ItemKind::TyAlias(ty, generics)
320             }
321             ItemKind::TyAlias(box TyAlias {
322                 ref generics, ref where_clauses, ty: None, ..
323             }) => {
324                 let mut generics = generics.clone();
325                 add_ty_alias_where_clause(&mut generics, *where_clauses, true);
326                 let (generics, ty) = self.lower_generics(
327                     &generics,
328                     id,
329                     &mut ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
330                     |this| this.arena.alloc(this.ty(span, hir::TyKind::Err)),
331                 );
332                 hir::ItemKind::TyAlias(ty, generics)
333             }
334             ItemKind::Enum(ref enum_definition, ref generics) => {
335                 let (generics, variants) = self.lower_generics(
336                     generics,
337                     id,
338                     &mut ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
339                     |this| {
340                         this.arena.alloc_from_iter(
341                             enum_definition.variants.iter().map(|x| this.lower_variant(x)),
342                         )
343                     },
344                 );
345                 hir::ItemKind::Enum(hir::EnumDef { variants }, generics)
346             }
347             ItemKind::Struct(ref struct_def, ref generics) => {
348                 let (generics, struct_def) = self.lower_generics(
349                     generics,
350                     id,
351                     &mut ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
352                     |this| this.lower_variant_data(hir_id, struct_def),
353                 );
354                 hir::ItemKind::Struct(struct_def, generics)
355             }
356             ItemKind::Union(ref vdata, ref generics) => {
357                 let (generics, vdata) = self.lower_generics(
358                     generics,
359                     id,
360                     &mut ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
361                     |this| this.lower_variant_data(hir_id, vdata),
362                 );
363                 hir::ItemKind::Union(vdata, generics)
364             }
365             ItemKind::Impl(box Impl {
366                 unsafety,
367                 polarity,
368                 defaultness,
369                 constness,
370                 generics: ref ast_generics,
371                 of_trait: ref trait_ref,
372                 self_ty: ref ty,
373                 items: ref impl_items,
374             }) => {
375                 // Lower the "impl header" first. This ordering is important
376                 // for in-band lifetimes! Consider `'a` here:
377                 //
378                 //     impl Foo<'a> for u32 {
379                 //         fn method(&'a self) { .. }
380                 //     }
381                 //
382                 // Because we start by lowering the `Foo<'a> for u32`
383                 // part, we will add `'a` to the list of generics on
384                 // the impl. When we then encounter it later in the
385                 // method, it will not be considered an in-band
386                 // lifetime to be added, but rather a reference to a
387                 // parent lifetime.
388                 let mut itctx = ImplTraitContext::Universal;
389                 let (generics, (trait_ref, lowered_ty)) =
390                     self.lower_generics(ast_generics, id, &mut itctx, |this| {
391                         let trait_ref = trait_ref.as_ref().map(|trait_ref| {
392                             this.lower_trait_ref(
393                                 trait_ref,
394                                 &mut ImplTraitContext::Disallowed(ImplTraitPosition::Trait),
395                             )
396                         });
397
398                         let lowered_ty = this.lower_ty(
399                             ty,
400                             &mut ImplTraitContext::Disallowed(ImplTraitPosition::Type),
401                         );
402
403                         (trait_ref, lowered_ty)
404                     });
405
406                 let new_impl_items = self
407                     .arena
408                     .alloc_from_iter(impl_items.iter().map(|item| self.lower_impl_item_ref(item)));
409
410                 // `defaultness.has_value()` is never called for an `impl`, always `true` in order
411                 // to not cause an assertion failure inside the `lower_defaultness` function.
412                 let has_val = true;
413                 let (defaultness, defaultness_span) = self.lower_defaultness(defaultness, has_val);
414                 let polarity = match polarity {
415                     ImplPolarity::Positive => ImplPolarity::Positive,
416                     ImplPolarity::Negative(s) => ImplPolarity::Negative(self.lower_span(s)),
417                 };
418                 hir::ItemKind::Impl(self.arena.alloc(hir::Impl {
419                     unsafety: self.lower_unsafety(unsafety),
420                     polarity,
421                     defaultness,
422                     defaultness_span,
423                     constness: self.lower_constness(constness),
424                     generics,
425                     of_trait: trait_ref,
426                     self_ty: lowered_ty,
427                     items: new_impl_items,
428                 }))
429             }
430             ItemKind::Trait(box Trait {
431                 is_auto,
432                 unsafety,
433                 ref generics,
434                 ref bounds,
435                 ref items,
436             }) => {
437                 let (generics, (unsafety, items, bounds)) = self.lower_generics(
438                     generics,
439                     id,
440                     &mut ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
441                     |this| {
442                         let bounds = this.lower_param_bounds(
443                             bounds,
444                             &mut ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
445                         );
446                         let items = this.arena.alloc_from_iter(
447                             items.iter().map(|item| this.lower_trait_item_ref(item)),
448                         );
449                         let unsafety = this.lower_unsafety(unsafety);
450                         (unsafety, items, bounds)
451                     },
452                 );
453                 hir::ItemKind::Trait(is_auto, unsafety, generics, bounds, items)
454             }
455             ItemKind::TraitAlias(ref generics, ref bounds) => {
456                 let (generics, bounds) = self.lower_generics(
457                     generics,
458                     id,
459                     &mut ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
460                     |this| {
461                         this.lower_param_bounds(
462                             bounds,
463                             &mut ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
464                         )
465                     },
466                 );
467                 hir::ItemKind::TraitAlias(generics, bounds)
468             }
469             ItemKind::MacroDef(MacroDef { ref body, macro_rules }) => {
470                 let body = P(self.lower_mac_args(body));
471                 let macro_kind = self.resolver.decl_macro_kind(self.local_def_id(id));
472                 hir::ItemKind::Macro(ast::MacroDef { body, macro_rules }, macro_kind)
473             }
474             ItemKind::MacCall(..) => {
475                 panic!("`TyMac` should have been expanded by now")
476             }
477         }
478     }
479
480     fn lower_const_item(
481         &mut self,
482         ty: &Ty,
483         span: Span,
484         body: Option<&Expr>,
485     ) -> (&'hir hir::Ty<'hir>, hir::BodyId) {
486         let ty = self.lower_ty(ty, &mut ImplTraitContext::Disallowed(ImplTraitPosition::Type));
487         (ty, self.lower_const_body(span, body))
488     }
489
490     #[instrument(level = "debug", skip(self))]
491     fn lower_use_tree(
492         &mut self,
493         tree: &UseTree,
494         prefix: &Path,
495         id: NodeId,
496         vis_span: Span,
497         ident: &mut Ident,
498         attrs: Option<&'hir [Attribute]>,
499     ) -> hir::ItemKind<'hir> {
500         let path = &tree.prefix;
501         let segments = prefix.segments.iter().chain(path.segments.iter()).cloned().collect();
502
503         match tree.kind {
504             UseTreeKind::Simple(rename, id1, id2) => {
505                 *ident = tree.ident();
506
507                 // First, apply the prefix to the path.
508                 let mut path = Path { segments, span: path.span, tokens: None };
509
510                 // Correctly resolve `self` imports.
511                 if path.segments.len() > 1
512                     && path.segments.last().unwrap().ident.name == kw::SelfLower
513                 {
514                     let _ = path.segments.pop();
515                     if rename.is_none() {
516                         *ident = path.segments.last().unwrap().ident;
517                     }
518                 }
519
520                 let mut resolutions = self.expect_full_res_from_use(id).fuse();
521                 // We want to return *something* from this function, so hold onto the first item
522                 // for later.
523                 let ret_res = self.lower_res(resolutions.next().unwrap_or(Res::Err));
524
525                 // Here, we are looping over namespaces, if they exist for the definition
526                 // being imported. We only handle type and value namespaces because we
527                 // won't be dealing with macros in the rest of the compiler.
528                 // Essentially a single `use` which imports two names is desugared into
529                 // two imports.
530                 for new_node_id in [id1, id2] {
531                     let new_id = self.local_def_id(new_node_id);
532                     let Some(res) = resolutions.next() else {
533                         // Associate an HirId to both ids even if there is no resolution.
534                         let _old = self.children.insert(
535                             new_id,
536                             hir::MaybeOwner::NonOwner(hir::HirId::make_owner(new_id)),
537                         );
538                         debug_assert!(_old.is_none());
539                         continue;
540                     };
541                     let ident = *ident;
542                     let mut path = path.clone();
543                     for seg in &mut path.segments {
544                         seg.id = self.next_node_id();
545                     }
546                     let span = path.span;
547
548                     self.with_hir_id_owner(new_node_id, |this| {
549                         let res = this.lower_res(res);
550                         let path = this.lower_path_extra(res, &path, ParamMode::Explicit);
551                         let kind = hir::ItemKind::Use(path, hir::UseKind::Single);
552                         if let Some(attrs) = attrs {
553                             this.attrs.insert(hir::ItemLocalId::new(0), attrs);
554                         }
555
556                         let item = hir::Item {
557                             def_id: new_id,
558                             ident: this.lower_ident(ident),
559                             kind,
560                             vis_span,
561                             span: this.lower_span(span),
562                         };
563                         hir::OwnerNode::Item(this.arena.alloc(item))
564                     });
565                 }
566
567                 let path = self.lower_path_extra(ret_res, &path, ParamMode::Explicit);
568                 hir::ItemKind::Use(path, hir::UseKind::Single)
569             }
570             UseTreeKind::Glob => {
571                 let path = self.lower_path(
572                     id,
573                     &Path { segments, span: path.span, tokens: None },
574                     ParamMode::Explicit,
575                 );
576                 hir::ItemKind::Use(path, hir::UseKind::Glob)
577             }
578             UseTreeKind::Nested(ref trees) => {
579                 // Nested imports are desugared into simple imports.
580                 // So, if we start with
581                 //
582                 // ```
583                 // pub(x) use foo::{a, b};
584                 // ```
585                 //
586                 // we will create three items:
587                 //
588                 // ```
589                 // pub(x) use foo::a;
590                 // pub(x) use foo::b;
591                 // pub(x) use foo::{}; // <-- this is called the `ListStem`
592                 // ```
593                 //
594                 // The first two are produced by recursively invoking
595                 // `lower_use_tree` (and indeed there may be things
596                 // like `use foo::{a::{b, c}}` and so forth).  They
597                 // wind up being directly added to
598                 // `self.items`. However, the structure of this
599                 // function also requires us to return one item, and
600                 // for that we return the `{}` import (called the
601                 // `ListStem`).
602
603                 let prefix = Path { segments, span: prefix.span.to(path.span), tokens: None };
604
605                 // Add all the nested `PathListItem`s to the HIR.
606                 for &(ref use_tree, id) in trees {
607                     let new_hir_id = self.local_def_id(id);
608
609                     let mut prefix = prefix.clone();
610
611                     // Give the segments new node-ids since they are being cloned.
612                     for seg in &mut prefix.segments {
613                         seg.id = self.next_node_id();
614                     }
615
616                     // Each `use` import is an item and thus are owners of the
617                     // names in the path. Up to this point the nested import is
618                     // the current owner, since we want each desugared import to
619                     // own its own names, we have to adjust the owner before
620                     // lowering the rest of the import.
621                     self.with_hir_id_owner(id, |this| {
622                         let mut ident = *ident;
623
624                         let kind =
625                             this.lower_use_tree(use_tree, &prefix, id, vis_span, &mut ident, attrs);
626                         if let Some(attrs) = attrs {
627                             this.attrs.insert(hir::ItemLocalId::new(0), attrs);
628                         }
629
630                         let item = hir::Item {
631                             def_id: new_hir_id,
632                             ident: this.lower_ident(ident),
633                             kind,
634                             vis_span,
635                             span: this.lower_span(use_tree.span),
636                         };
637                         hir::OwnerNode::Item(this.arena.alloc(item))
638                     });
639                 }
640
641                 let res = self.expect_full_res_from_use(id).next().unwrap_or(Res::Err);
642                 let res = self.lower_res(res);
643                 let path = self.lower_path_extra(res, &prefix, ParamMode::Explicit);
644                 hir::ItemKind::Use(path, hir::UseKind::ListStem)
645             }
646         }
647     }
648
649     fn lower_foreign_item(&mut self, i: &ForeignItem) -> &'hir hir::ForeignItem<'hir> {
650         let hir_id = self.lower_node_id(i.id);
651         let def_id = hir_id.expect_owner();
652         self.lower_attrs(hir_id, &i.attrs);
653         let item = hir::ForeignItem {
654             def_id,
655             ident: self.lower_ident(i.ident),
656             kind: match i.kind {
657                 ForeignItemKind::Fn(box Fn { ref sig, ref generics, .. }) => {
658                     let fdec = &sig.decl;
659                     let mut itctx = ImplTraitContext::Universal;
660                     let (generics, (fn_dec, fn_args)) =
661                         self.lower_generics(generics, i.id, &mut itctx, |this| {
662                             (
663                                 // Disallow `impl Trait` in foreign items.
664                                 this.lower_fn_decl(
665                                     fdec,
666                                     None,
667                                     sig.span,
668                                     FnDeclKind::ExternFn,
669                                     None,
670                                 ),
671                                 this.lower_fn_params_to_names(fdec),
672                             )
673                         });
674
675                     hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
676                 }
677                 ForeignItemKind::Static(ref t, m, _) => {
678                     let ty = self
679                         .lower_ty(t, &mut ImplTraitContext::Disallowed(ImplTraitPosition::Type));
680                     hir::ForeignItemKind::Static(ty, m)
681                 }
682                 ForeignItemKind::TyAlias(..) => hir::ForeignItemKind::Type,
683                 ForeignItemKind::MacCall(_) => panic!("macro shouldn't exist here"),
684             },
685             vis_span: self.lower_span(i.vis.span),
686             span: self.lower_span(i.span),
687         };
688         self.arena.alloc(item)
689     }
690
691     fn lower_foreign_item_ref(&mut self, i: &ForeignItem) -> hir::ForeignItemRef {
692         hir::ForeignItemRef {
693             id: hir::ForeignItemId { def_id: self.local_def_id(i.id) },
694             ident: self.lower_ident(i.ident),
695             span: self.lower_span(i.span),
696         }
697     }
698
699     fn lower_variant(&mut self, v: &Variant) -> hir::Variant<'hir> {
700         let id = self.lower_node_id(v.id);
701         self.lower_attrs(id, &v.attrs);
702         hir::Variant {
703             id,
704             data: self.lower_variant_data(id, &v.data),
705             disr_expr: v.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
706             ident: self.lower_ident(v.ident),
707             span: self.lower_span(v.span),
708         }
709     }
710
711     fn lower_variant_data(
712         &mut self,
713         parent_id: hir::HirId,
714         vdata: &VariantData,
715     ) -> hir::VariantData<'hir> {
716         match *vdata {
717             VariantData::Struct(ref fields, recovered) => hir::VariantData::Struct(
718                 self.arena
719                     .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_field_def(f))),
720                 recovered,
721             ),
722             VariantData::Tuple(ref fields, id) => {
723                 let ctor_id = self.lower_node_id(id);
724                 self.alias_attrs(ctor_id, parent_id);
725                 hir::VariantData::Tuple(
726                     self.arena.alloc_from_iter(
727                         fields.iter().enumerate().map(|f| self.lower_field_def(f)),
728                     ),
729                     ctor_id,
730                 )
731             }
732             VariantData::Unit(id) => {
733                 let ctor_id = self.lower_node_id(id);
734                 self.alias_attrs(ctor_id, parent_id);
735                 hir::VariantData::Unit(ctor_id)
736             }
737         }
738     }
739
740     fn lower_field_def(&mut self, (index, f): (usize, &FieldDef)) -> hir::FieldDef<'hir> {
741         let ty = if let TyKind::Path(ref qself, ref path) = f.ty.kind {
742             let t = self.lower_path_ty(
743                 &f.ty,
744                 qself,
745                 path,
746                 ParamMode::ExplicitNamed, // no `'_` in declarations (Issue #61124)
747                 &mut ImplTraitContext::Disallowed(ImplTraitPosition::Path),
748             );
749             self.arena.alloc(t)
750         } else {
751             self.lower_ty(&f.ty, &mut ImplTraitContext::Disallowed(ImplTraitPosition::Type))
752         };
753         let hir_id = self.lower_node_id(f.id);
754         self.lower_attrs(hir_id, &f.attrs);
755         hir::FieldDef {
756             span: self.lower_span(f.span),
757             hir_id,
758             ident: match f.ident {
759                 Some(ident) => self.lower_ident(ident),
760                 // FIXME(jseyfried): positional field hygiene.
761                 None => Ident::new(sym::integer(index), self.lower_span(f.span)),
762             },
763             vis_span: self.lower_span(f.vis.span),
764             ty,
765         }
766     }
767
768     fn lower_trait_item(&mut self, i: &AssocItem) -> &'hir hir::TraitItem<'hir> {
769         let hir_id = self.lower_node_id(i.id);
770         let trait_item_def_id = hir_id.expect_owner();
771
772         let (generics, kind, has_default) = match i.kind {
773             AssocItemKind::Const(_, ref ty, ref default) => {
774                 let ty =
775                     self.lower_ty(ty, &mut ImplTraitContext::Disallowed(ImplTraitPosition::Type));
776                 let body = default.as_ref().map(|x| self.lower_const_body(i.span, Some(x)));
777                 (hir::Generics::empty(), hir::TraitItemKind::Const(ty, body), body.is_some())
778             }
779             AssocItemKind::Fn(box Fn { ref sig, ref generics, body: None, .. }) => {
780                 let asyncness = sig.header.asyncness;
781                 let names = self.lower_fn_params_to_names(&sig.decl);
782                 let (generics, sig) = self.lower_method_sig(
783                     generics,
784                     sig,
785                     i.id,
786                     FnDeclKind::Trait,
787                     asyncness.opt_return_id(),
788                 );
789                 (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Required(names)), false)
790             }
791             AssocItemKind::Fn(box Fn { ref sig, ref generics, body: Some(ref body), .. }) => {
792                 let asyncness = sig.header.asyncness;
793                 let body_id =
794                     self.lower_maybe_async_body(i.span, &sig.decl, asyncness, Some(&body));
795                 let (generics, sig) = self.lower_method_sig(
796                     generics,
797                     sig,
798                     i.id,
799                     FnDeclKind::Trait,
800                     asyncness.opt_return_id(),
801                 );
802                 (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Provided(body_id)), true)
803             }
804             AssocItemKind::TyAlias(box TyAlias {
805                 ref generics,
806                 where_clauses,
807                 ref bounds,
808                 ref ty,
809                 ..
810             }) => {
811                 let mut generics = generics.clone();
812                 add_ty_alias_where_clause(&mut generics, where_clauses, false);
813                 let (generics, kind) = self.lower_generics(
814                     &generics,
815                     i.id,
816                     &mut ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
817                     |this| {
818                         let ty = ty.as_ref().map(|x| {
819                             this.lower_ty(
820                                 x,
821                                 &mut ImplTraitContext::Disallowed(ImplTraitPosition::Type),
822                             )
823                         });
824                         hir::TraitItemKind::Type(
825                             this.lower_param_bounds(
826                                 bounds,
827                                 &mut ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
828                             ),
829                             ty,
830                         )
831                     },
832                 );
833                 (generics, kind, ty.is_some())
834             }
835             AssocItemKind::MacCall(..) => panic!("macro item shouldn't exist at this point"),
836         };
837
838         self.lower_attrs(hir_id, &i.attrs);
839         let item = hir::TraitItem {
840             def_id: trait_item_def_id,
841             ident: self.lower_ident(i.ident),
842             generics,
843             kind,
844             span: self.lower_span(i.span),
845             defaultness: hir::Defaultness::Default { has_value: has_default },
846         };
847         self.arena.alloc(item)
848     }
849
850     fn lower_trait_item_ref(&mut self, i: &AssocItem) -> hir::TraitItemRef {
851         let kind = match &i.kind {
852             AssocItemKind::Const(..) => hir::AssocItemKind::Const,
853             AssocItemKind::TyAlias(..) => hir::AssocItemKind::Type,
854             AssocItemKind::Fn(box Fn { sig, .. }) => {
855                 hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }
856             }
857             AssocItemKind::MacCall(..) => unimplemented!(),
858         };
859         let id = hir::TraitItemId { def_id: self.local_def_id(i.id) };
860         hir::TraitItemRef {
861             id,
862             ident: self.lower_ident(i.ident),
863             span: self.lower_span(i.span),
864             kind,
865         }
866     }
867
868     /// Construct `ExprKind::Err` for the given `span`.
869     pub(crate) fn expr_err(&mut self, span: Span) -> hir::Expr<'hir> {
870         self.expr(span, hir::ExprKind::Err, AttrVec::new())
871     }
872
873     fn lower_impl_item(&mut self, i: &AssocItem) -> &'hir hir::ImplItem<'hir> {
874         // Since `default impl` is not yet implemented, this is always true in impls.
875         let has_value = true;
876         let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value);
877
878         let (generics, kind) = match &i.kind {
879             AssocItemKind::Const(_, ty, expr) => {
880                 let ty =
881                     self.lower_ty(ty, &mut ImplTraitContext::Disallowed(ImplTraitPosition::Type));
882                 (
883                     hir::Generics::empty(),
884                     hir::ImplItemKind::Const(ty, self.lower_const_body(i.span, expr.as_deref())),
885                 )
886             }
887             AssocItemKind::Fn(box Fn { sig, generics, body, .. }) => {
888                 self.current_item = Some(i.span);
889                 let asyncness = sig.header.asyncness;
890                 let body_id =
891                     self.lower_maybe_async_body(i.span, &sig.decl, asyncness, body.as_deref());
892                 let (generics, sig) = self.lower_method_sig(
893                     generics,
894                     sig,
895                     i.id,
896                     if self.is_in_trait_impl { FnDeclKind::Impl } else { FnDeclKind::Inherent },
897                     asyncness.opt_return_id(),
898                 );
899
900                 (generics, hir::ImplItemKind::Fn(sig, body_id))
901             }
902             AssocItemKind::TyAlias(box TyAlias { generics, where_clauses, ty, .. }) => {
903                 let mut generics = generics.clone();
904                 add_ty_alias_where_clause(&mut generics, *where_clauses, false);
905                 self.lower_generics(
906                     &generics,
907                     i.id,
908                     &mut ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
909                     |this| match ty {
910                         None => {
911                             let ty = this.arena.alloc(this.ty(i.span, hir::TyKind::Err));
912                             hir::ImplItemKind::TyAlias(ty)
913                         }
914                         Some(ty) => {
915                             let ty = this.lower_ty(ty, &mut ImplTraitContext::TypeAliasesOpaqueTy);
916                             hir::ImplItemKind::TyAlias(ty)
917                         }
918                     },
919                 )
920             }
921             AssocItemKind::MacCall(..) => panic!("`TyMac` should have been expanded by now"),
922         };
923
924         let hir_id = self.lower_node_id(i.id);
925         self.lower_attrs(hir_id, &i.attrs);
926         let item = hir::ImplItem {
927             def_id: hir_id.expect_owner(),
928             ident: self.lower_ident(i.ident),
929             generics,
930             kind,
931             vis_span: self.lower_span(i.vis.span),
932             span: self.lower_span(i.span),
933             defaultness,
934         };
935         self.arena.alloc(item)
936     }
937
938     fn lower_impl_item_ref(&mut self, i: &AssocItem) -> hir::ImplItemRef {
939         hir::ImplItemRef {
940             id: hir::ImplItemId { def_id: self.local_def_id(i.id) },
941             ident: self.lower_ident(i.ident),
942             span: self.lower_span(i.span),
943             kind: match &i.kind {
944                 AssocItemKind::Const(..) => hir::AssocItemKind::Const,
945                 AssocItemKind::TyAlias(..) => hir::AssocItemKind::Type,
946                 AssocItemKind::Fn(box Fn { sig, .. }) => {
947                     hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }
948                 }
949                 AssocItemKind::MacCall(..) => unimplemented!(),
950             },
951             trait_item_def_id: self.resolver.get_partial_res(i.id).map(|r| r.base_res().def_id()),
952         }
953     }
954
955     fn lower_defaultness(
956         &self,
957         d: Defaultness,
958         has_value: bool,
959     ) -> (hir::Defaultness, Option<Span>) {
960         match d {
961             Defaultness::Default(sp) => {
962                 (hir::Defaultness::Default { has_value }, Some(self.lower_span(sp)))
963             }
964             Defaultness::Final => {
965                 assert!(has_value);
966                 (hir::Defaultness::Final, None)
967             }
968         }
969     }
970
971     fn record_body(
972         &mut self,
973         params: &'hir [hir::Param<'hir>],
974         value: hir::Expr<'hir>,
975     ) -> hir::BodyId {
976         let body = hir::Body {
977             generator_kind: self.generator_kind,
978             params,
979             value: self.arena.alloc(value),
980         };
981         let id = body.id();
982         debug_assert_eq!(id.hir_id.owner, self.current_hir_id_owner);
983         self.bodies.push((id.hir_id.local_id, self.arena.alloc(body)));
984         id
985     }
986
987     pub(super) fn lower_body(
988         &mut self,
989         f: impl FnOnce(&mut Self) -> (&'hir [hir::Param<'hir>], hir::Expr<'hir>),
990     ) -> hir::BodyId {
991         let prev_gen_kind = self.generator_kind.take();
992         let task_context = self.task_context.take();
993         let (parameters, result) = f(self);
994         let body_id = self.record_body(parameters, result);
995         self.task_context = task_context;
996         self.generator_kind = prev_gen_kind;
997         body_id
998     }
999
1000     fn lower_param(&mut self, param: &Param) -> hir::Param<'hir> {
1001         let hir_id = self.lower_node_id(param.id);
1002         self.lower_attrs(hir_id, &param.attrs);
1003         hir::Param {
1004             hir_id,
1005             pat: self.lower_pat(&param.pat),
1006             ty_span: self.lower_span(param.ty.span),
1007             span: self.lower_span(param.span),
1008         }
1009     }
1010
1011     pub(super) fn lower_fn_body(
1012         &mut self,
1013         decl: &FnDecl,
1014         body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
1015     ) -> hir::BodyId {
1016         self.lower_body(|this| {
1017             (
1018                 this.arena.alloc_from_iter(decl.inputs.iter().map(|x| this.lower_param(x))),
1019                 body(this),
1020             )
1021         })
1022     }
1023
1024     fn lower_fn_body_block(
1025         &mut self,
1026         span: Span,
1027         decl: &FnDecl,
1028         body: Option<&Block>,
1029     ) -> hir::BodyId {
1030         self.lower_fn_body(decl, |this| this.lower_block_expr_opt(span, body))
1031     }
1032
1033     fn lower_block_expr_opt(&mut self, span: Span, block: Option<&Block>) -> hir::Expr<'hir> {
1034         match block {
1035             Some(block) => self.lower_block_expr(block),
1036             None => self.expr_err(span),
1037         }
1038     }
1039
1040     pub(super) fn lower_const_body(&mut self, span: Span, expr: Option<&Expr>) -> hir::BodyId {
1041         self.lower_body(|this| {
1042             (
1043                 &[],
1044                 match expr {
1045                     Some(expr) => this.lower_expr_mut(expr),
1046                     None => this.expr_err(span),
1047                 },
1048             )
1049         })
1050     }
1051
1052     fn lower_maybe_async_body(
1053         &mut self,
1054         span: Span,
1055         decl: &FnDecl,
1056         asyncness: Async,
1057         body: Option<&Block>,
1058     ) -> hir::BodyId {
1059         let closure_id = match asyncness {
1060             Async::Yes { closure_id, .. } => closure_id,
1061             Async::No => return self.lower_fn_body_block(span, decl, body),
1062         };
1063
1064         self.lower_body(|this| {
1065             let mut parameters: Vec<hir::Param<'_>> = Vec::new();
1066             let mut statements: Vec<hir::Stmt<'_>> = Vec::new();
1067
1068             // Async function parameters are lowered into the closure body so that they are
1069             // captured and so that the drop order matches the equivalent non-async functions.
1070             //
1071             // from:
1072             //
1073             //     async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
1074             //         <body>
1075             //     }
1076             //
1077             // into:
1078             //
1079             //     fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
1080             //       async move {
1081             //         let __arg2 = __arg2;
1082             //         let <pattern> = __arg2;
1083             //         let __arg1 = __arg1;
1084             //         let <pattern> = __arg1;
1085             //         let __arg0 = __arg0;
1086             //         let <pattern> = __arg0;
1087             //         drop-temps { <body> } // see comments later in fn for details
1088             //       }
1089             //     }
1090             //
1091             // If `<pattern>` is a simple ident, then it is lowered to a single
1092             // `let <pattern> = <pattern>;` statement as an optimization.
1093             //
1094             // Note that the body is embedded in `drop-temps`; an
1095             // equivalent desugaring would be `return { <body>
1096             // };`. The key point is that we wish to drop all the
1097             // let-bound variables and temporaries created in the body
1098             // (and its tail expression!) before we drop the
1099             // parameters (c.f. rust-lang/rust#64512).
1100             for (index, parameter) in decl.inputs.iter().enumerate() {
1101                 let parameter = this.lower_param(parameter);
1102                 let span = parameter.pat.span;
1103
1104                 // Check if this is a binding pattern, if so, we can optimize and avoid adding a
1105                 // `let <pat> = __argN;` statement. In this case, we do not rename the parameter.
1106                 let (ident, is_simple_parameter) = match parameter.pat.kind {
1107                     hir::PatKind::Binding(hir::BindingAnnotation(ByRef::No, _), _, ident, _) => {
1108                         (ident, true)
1109                     }
1110                     // For `ref mut` or wildcard arguments, we can't reuse the binding, but
1111                     // we can keep the same name for the parameter.
1112                     // This lets rustdoc render it correctly in documentation.
1113                     hir::PatKind::Binding(_, _, ident, _) => (ident, false),
1114                     hir::PatKind::Wild => {
1115                         (Ident::with_dummy_span(rustc_span::symbol::kw::Underscore), false)
1116                     }
1117                     _ => {
1118                         // Replace the ident for bindings that aren't simple.
1119                         let name = format!("__arg{}", index);
1120                         let ident = Ident::from_str(&name);
1121
1122                         (ident, false)
1123                     }
1124                 };
1125
1126                 let desugared_span = this.mark_span_with_reason(DesugaringKind::Async, span, None);
1127
1128                 // Construct a parameter representing `__argN: <ty>` to replace the parameter of the
1129                 // async function.
1130                 //
1131                 // If this is the simple case, this parameter will end up being the same as the
1132                 // original parameter, but with a different pattern id.
1133                 let stmt_attrs = this.attrs.get(&parameter.hir_id.local_id).copied();
1134                 let (new_parameter_pat, new_parameter_id) = this.pat_ident(desugared_span, ident);
1135                 let new_parameter = hir::Param {
1136                     hir_id: parameter.hir_id,
1137                     pat: new_parameter_pat,
1138                     ty_span: this.lower_span(parameter.ty_span),
1139                     span: this.lower_span(parameter.span),
1140                 };
1141
1142                 if is_simple_parameter {
1143                     // If this is the simple case, then we only insert one statement that is
1144                     // `let <pat> = <pat>;`. We re-use the original argument's pattern so that
1145                     // `HirId`s are densely assigned.
1146                     let expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1147                     let stmt = this.stmt_let_pat(
1148                         stmt_attrs,
1149                         desugared_span,
1150                         Some(expr),
1151                         parameter.pat,
1152                         hir::LocalSource::AsyncFn,
1153                     );
1154                     statements.push(stmt);
1155                 } else {
1156                     // If this is not the simple case, then we construct two statements:
1157                     //
1158                     // ```
1159                     // let __argN = __argN;
1160                     // let <pat> = __argN;
1161                     // ```
1162                     //
1163                     // The first statement moves the parameter into the closure and thus ensures
1164                     // that the drop order is correct.
1165                     //
1166                     // The second statement creates the bindings that the user wrote.
1167
1168                     // Construct the `let mut __argN = __argN;` statement. It must be a mut binding
1169                     // because the user may have specified a `ref mut` binding in the next
1170                     // statement.
1171                     let (move_pat, move_id) = this.pat_ident_binding_mode(
1172                         desugared_span,
1173                         ident,
1174                         hir::BindingAnnotation::MUT,
1175                     );
1176                     let move_expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1177                     let move_stmt = this.stmt_let_pat(
1178                         None,
1179                         desugared_span,
1180                         Some(move_expr),
1181                         move_pat,
1182                         hir::LocalSource::AsyncFn,
1183                     );
1184
1185                     // Construct the `let <pat> = __argN;` statement. We re-use the original
1186                     // parameter's pattern so that `HirId`s are densely assigned.
1187                     let pattern_expr = this.expr_ident(desugared_span, ident, move_id);
1188                     let pattern_stmt = this.stmt_let_pat(
1189                         stmt_attrs,
1190                         desugared_span,
1191                         Some(pattern_expr),
1192                         parameter.pat,
1193                         hir::LocalSource::AsyncFn,
1194                     );
1195
1196                     statements.push(move_stmt);
1197                     statements.push(pattern_stmt);
1198                 };
1199
1200                 parameters.push(new_parameter);
1201             }
1202
1203             let body_span = body.map_or(span, |b| b.span);
1204             let async_expr = this.make_async_expr(
1205                 CaptureBy::Value,
1206                 closure_id,
1207                 None,
1208                 body_span,
1209                 hir::AsyncGeneratorKind::Fn,
1210                 |this| {
1211                     // Create a block from the user's function body:
1212                     let user_body = this.lower_block_expr_opt(body_span, body);
1213
1214                     // Transform into `drop-temps { <user-body> }`, an expression:
1215                     let desugared_span =
1216                         this.mark_span_with_reason(DesugaringKind::Async, user_body.span, None);
1217                     let user_body = this.expr_drop_temps(
1218                         desugared_span,
1219                         this.arena.alloc(user_body),
1220                         AttrVec::new(),
1221                     );
1222
1223                     // As noted above, create the final block like
1224                     //
1225                     // ```
1226                     // {
1227                     //   let $param_pattern = $raw_param;
1228                     //   ...
1229                     //   drop-temps { <user-body> }
1230                     // }
1231                     // ```
1232                     let body = this.block_all(
1233                         desugared_span,
1234                         this.arena.alloc_from_iter(statements),
1235                         Some(user_body),
1236                     );
1237
1238                     this.expr_block(body, AttrVec::new())
1239                 },
1240             );
1241
1242             (
1243                 this.arena.alloc_from_iter(parameters),
1244                 this.expr(body_span, async_expr, AttrVec::new()),
1245             )
1246         })
1247     }
1248
1249     fn lower_method_sig(
1250         &mut self,
1251         generics: &Generics,
1252         sig: &FnSig,
1253         id: NodeId,
1254         kind: FnDeclKind,
1255         is_async: Option<(NodeId, Span)>,
1256     ) -> (&'hir hir::Generics<'hir>, hir::FnSig<'hir>) {
1257         let header = self.lower_fn_header(sig.header);
1258         let mut itctx = ImplTraitContext::Universal;
1259         let (generics, decl) = self.lower_generics(generics, id, &mut itctx, |this| {
1260             this.lower_fn_decl(&sig.decl, Some(id), sig.span, kind, is_async)
1261         });
1262         (generics, hir::FnSig { header, decl, span: self.lower_span(sig.span) })
1263     }
1264
1265     fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
1266         hir::FnHeader {
1267             unsafety: self.lower_unsafety(h.unsafety),
1268             asyncness: self.lower_asyncness(h.asyncness),
1269             constness: self.lower_constness(h.constness),
1270             abi: self.lower_extern(h.ext),
1271         }
1272     }
1273
1274     pub(super) fn lower_abi(&mut self, abi: StrLit) -> abi::Abi {
1275         abi::lookup(abi.symbol_unescaped.as_str()).unwrap_or_else(|| {
1276             self.error_on_invalid_abi(abi);
1277             abi::Abi::Rust
1278         })
1279     }
1280
1281     pub(super) fn lower_extern(&mut self, ext: Extern) -> abi::Abi {
1282         match ext {
1283             Extern::None => abi::Abi::Rust,
1284             Extern::Implicit(_) => abi::Abi::FALLBACK,
1285             Extern::Explicit(abi, _) => self.lower_abi(abi),
1286         }
1287     }
1288
1289     fn error_on_invalid_abi(&self, abi: StrLit) {
1290         self.tcx.sess.emit_err(InvalidAbi {
1291             span: abi.span,
1292             abi: abi.symbol,
1293             valid_abis: abi::all_names().join(", "),
1294         });
1295     }
1296
1297     fn lower_asyncness(&mut self, a: Async) -> hir::IsAsync {
1298         match a {
1299             Async::Yes { .. } => hir::IsAsync::Async,
1300             Async::No => hir::IsAsync::NotAsync,
1301         }
1302     }
1303
1304     fn lower_constness(&mut self, c: Const) -> hir::Constness {
1305         match c {
1306             Const::Yes(_) => hir::Constness::Const,
1307             Const::No => hir::Constness::NotConst,
1308         }
1309     }
1310
1311     pub(super) fn lower_unsafety(&mut self, u: Unsafe) -> hir::Unsafety {
1312         match u {
1313             Unsafe::Yes(_) => hir::Unsafety::Unsafe,
1314             Unsafe::No => hir::Unsafety::Normal,
1315         }
1316     }
1317
1318     /// Return the pair of the lowered `generics` as `hir::Generics` and the evaluation of `f` with
1319     /// the carried impl trait definitions and bounds.
1320     #[instrument(level = "debug", skip(self, f))]
1321     fn lower_generics<T>(
1322         &mut self,
1323         generics: &Generics,
1324         parent_node_id: NodeId,
1325         itctx: &mut ImplTraitContext,
1326         f: impl FnOnce(&mut Self) -> T,
1327     ) -> (&'hir hir::Generics<'hir>, T) {
1328         debug_assert!(self.impl_trait_defs.is_empty());
1329         debug_assert!(self.impl_trait_bounds.is_empty());
1330
1331         // Error if `?Trait` bounds in where clauses don't refer directly to type parameters.
1332         // Note: we used to clone these bounds directly onto the type parameter (and avoid lowering
1333         // these into hir when we lower thee where clauses), but this makes it quite difficult to
1334         // keep track of the Span info. Now, `add_implicitly_sized` in `AstConv` checks both param bounds and
1335         // where clauses for `?Sized`.
1336         for pred in &generics.where_clause.predicates {
1337             let WherePredicate::BoundPredicate(ref bound_pred) = *pred else {
1338                 continue;
1339             };
1340             let compute_is_param = || {
1341                 // Check if the where clause type is a plain type parameter.
1342                 match self
1343                     .resolver
1344                     .get_partial_res(bound_pred.bounded_ty.id)
1345                     .map(|d| (d.base_res(), d.unresolved_segments()))
1346                 {
1347                     Some((Res::Def(DefKind::TyParam, def_id), 0))
1348                         if bound_pred.bound_generic_params.is_empty() =>
1349                     {
1350                         generics
1351                             .params
1352                             .iter()
1353                             .any(|p| def_id == self.local_def_id(p.id).to_def_id())
1354                     }
1355                     // Either the `bounded_ty` is not a plain type parameter, or
1356                     // it's not found in the generic type parameters list.
1357                     _ => false,
1358                 }
1359             };
1360             // We only need to compute this once per `WherePredicate`, but don't
1361             // need to compute this at all unless there is a Maybe bound.
1362             let mut is_param: Option<bool> = None;
1363             for bound in &bound_pred.bounds {
1364                 if !matches!(*bound, GenericBound::Trait(_, TraitBoundModifier::Maybe)) {
1365                     continue;
1366                 }
1367                 let is_param = *is_param.get_or_insert_with(compute_is_param);
1368                 if !is_param {
1369                     self.tcx.sess.emit_err(MisplacedRelaxTraitBound { span: bound.span() });
1370                 }
1371             }
1372         }
1373
1374         let mut predicates: SmallVec<[hir::WherePredicate<'hir>; 4]> = SmallVec::new();
1375         predicates.extend(generics.params.iter().filter_map(|param| {
1376             self.lower_generic_bound_predicate(
1377                 param.ident,
1378                 param.id,
1379                 &param.kind,
1380                 &param.bounds,
1381                 itctx,
1382                 PredicateOrigin::GenericParam,
1383             )
1384         }));
1385         predicates.extend(
1386             generics
1387                 .where_clause
1388                 .predicates
1389                 .iter()
1390                 .map(|predicate| self.lower_where_predicate(predicate)),
1391         );
1392
1393         let mut params: SmallVec<[hir::GenericParam<'hir>; 4]> =
1394             self.lower_generic_params_mut(&generics.params).collect();
1395
1396         // Introduce extra lifetimes if late resolution tells us to.
1397         let extra_lifetimes = self.resolver.take_extra_lifetime_params(parent_node_id);
1398         params.extend(extra_lifetimes.into_iter().filter_map(|(ident, node_id, res)| {
1399             self.lifetime_res_to_generic_param(ident, node_id, res)
1400         }));
1401
1402         let has_where_clause_predicates = !generics.where_clause.predicates.is_empty();
1403         let where_clause_span = self.lower_span(generics.where_clause.span);
1404         let span = self.lower_span(generics.span);
1405         let res = f(self);
1406
1407         let impl_trait_defs = std::mem::take(&mut self.impl_trait_defs);
1408         params.extend(impl_trait_defs.into_iter());
1409
1410         let impl_trait_bounds = std::mem::take(&mut self.impl_trait_bounds);
1411         predicates.extend(impl_trait_bounds.into_iter());
1412
1413         let lowered_generics = self.arena.alloc(hir::Generics {
1414             params: self.arena.alloc_from_iter(params),
1415             predicates: self.arena.alloc_from_iter(predicates),
1416             has_where_clause_predicates,
1417             where_clause_span,
1418             span,
1419         });
1420
1421         (lowered_generics, res)
1422     }
1423
1424     pub(super) fn lower_generic_bound_predicate(
1425         &mut self,
1426         ident: Ident,
1427         id: NodeId,
1428         kind: &GenericParamKind,
1429         bounds: &[GenericBound],
1430         itctx: &mut ImplTraitContext,
1431         origin: PredicateOrigin,
1432     ) -> Option<hir::WherePredicate<'hir>> {
1433         // Do not create a clause if we do not have anything inside it.
1434         if bounds.is_empty() {
1435             return None;
1436         }
1437
1438         let bounds = self.lower_param_bounds(bounds, itctx);
1439
1440         let ident = self.lower_ident(ident);
1441         let param_span = ident.span;
1442         let span = bounds
1443             .iter()
1444             .fold(Some(param_span.shrink_to_hi()), |span: Option<Span>, bound| {
1445                 let bound_span = bound.span();
1446                 // We include bounds that come from a `#[derive(_)]` but point at the user's code,
1447                 // as we use this method to get a span appropriate for suggestions.
1448                 if !bound_span.can_be_used_for_suggestions() {
1449                     None
1450                 } else if let Some(span) = span {
1451                     Some(span.to(bound_span))
1452                 } else {
1453                     Some(bound_span)
1454                 }
1455             })
1456             .unwrap_or(param_span.shrink_to_hi());
1457         match kind {
1458             GenericParamKind::Const { .. } => None,
1459             GenericParamKind::Type { .. } => {
1460                 let def_id = self.local_def_id(id).to_def_id();
1461                 let hir_id = self.next_id();
1462                 let res = Res::Def(DefKind::TyParam, def_id);
1463                 let ty_path = self.arena.alloc(hir::Path {
1464                     span: param_span,
1465                     res,
1466                     segments: self
1467                         .arena
1468                         .alloc_from_iter([hir::PathSegment::new(ident, hir_id, res)]),
1469                 });
1470                 let ty_id = self.next_id();
1471                 let bounded_ty =
1472                     self.ty_path(ty_id, param_span, hir::QPath::Resolved(None, ty_path));
1473                 Some(hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1474                     bounded_ty: self.arena.alloc(bounded_ty),
1475                     bounds,
1476                     span,
1477                     bound_generic_params: &[],
1478                     origin,
1479                 }))
1480             }
1481             GenericParamKind::Lifetime => {
1482                 let ident_span = self.lower_span(ident.span);
1483                 let ident = self.lower_ident(ident);
1484                 let lt_id = self.next_node_id();
1485                 let lifetime = self.new_named_lifetime(id, lt_id, ident_span, ident);
1486                 Some(hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1487                     lifetime,
1488                     span,
1489                     bounds,
1490                     in_where_clause: false,
1491                 }))
1492             }
1493         }
1494     }
1495
1496     fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate<'hir> {
1497         match *pred {
1498             WherePredicate::BoundPredicate(WhereBoundPredicate {
1499                 ref bound_generic_params,
1500                 ref bounded_ty,
1501                 ref bounds,
1502                 span,
1503             }) => hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1504                 bound_generic_params: self.lower_generic_params(bound_generic_params),
1505                 bounded_ty: self.lower_ty(
1506                     bounded_ty,
1507                     &mut ImplTraitContext::Disallowed(ImplTraitPosition::Type),
1508                 ),
1509                 bounds: self.arena.alloc_from_iter(bounds.iter().map(|bound| {
1510                     self.lower_param_bound(
1511                         bound,
1512                         &mut ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
1513                     )
1514                 })),
1515                 span: self.lower_span(span),
1516                 origin: PredicateOrigin::WhereClause,
1517             }),
1518             WherePredicate::RegionPredicate(WhereRegionPredicate {
1519                 ref lifetime,
1520                 ref bounds,
1521                 span,
1522             }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1523                 span: self.lower_span(span),
1524                 lifetime: self.lower_lifetime(lifetime),
1525                 bounds: self.lower_param_bounds(
1526                     bounds,
1527                     &mut ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
1528                 ),
1529                 in_where_clause: true,
1530             }),
1531             WherePredicate::EqPredicate(WhereEqPredicate { ref lhs_ty, ref rhs_ty, span }) => {
1532                 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1533                     lhs_ty: self.lower_ty(
1534                         lhs_ty,
1535                         &mut ImplTraitContext::Disallowed(ImplTraitPosition::Type),
1536                     ),
1537                     rhs_ty: self.lower_ty(
1538                         rhs_ty,
1539                         &mut ImplTraitContext::Disallowed(ImplTraitPosition::Type),
1540                     ),
1541                     span: self.lower_span(span),
1542                 })
1543             }
1544         }
1545     }
1546 }