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