]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast_lowering/src/item.rs
Rollup merge of #101501 - Jarcho:tcx_lint_passes, r=davidtwco
[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 mut itctx = ImplTraitContext::Universal;
268                     let (generics, decl) = this.lower_generics(generics, id, &mut 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                     &mut ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
315                     |this| this.lower_ty(ty, &mut 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                     &mut 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                     &mut 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                     &mut 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                     &mut 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 mut itctx = ImplTraitContext::Universal;
387                 let (generics, (trait_ref, lowered_ty)) =
388                     self.lower_generics(ast_generics, id, &mut itctx, |this| {
389                         let trait_ref = trait_ref.as_ref().map(|trait_ref| {
390                             this.lower_trait_ref(
391                                 trait_ref,
392                                 &mut ImplTraitContext::Disallowed(ImplTraitPosition::Trait),
393                             )
394                         });
395
396                         let lowered_ty = this.lower_ty(
397                             ty,
398                             &mut ImplTraitContext::Disallowed(ImplTraitPosition::Type),
399                         );
400
401                         (trait_ref, lowered_ty)
402                     });
403
404                 let new_impl_items = self
405                     .arena
406                     .alloc_from_iter(impl_items.iter().map(|item| self.lower_impl_item_ref(item)));
407
408                 // `defaultness.has_value()` is never called for an `impl`, always `true` in order
409                 // to not cause an assertion failure inside the `lower_defaultness` function.
410                 let has_val = true;
411                 let (defaultness, defaultness_span) = self.lower_defaultness(defaultness, has_val);
412                 let polarity = match polarity {
413                     ImplPolarity::Positive => ImplPolarity::Positive,
414                     ImplPolarity::Negative(s) => ImplPolarity::Negative(self.lower_span(s)),
415                 };
416                 hir::ItemKind::Impl(self.arena.alloc(hir::Impl {
417                     unsafety: self.lower_unsafety(unsafety),
418                     polarity,
419                     defaultness,
420                     defaultness_span,
421                     constness: self.lower_constness(constness),
422                     generics,
423                     of_trait: trait_ref,
424                     self_ty: lowered_ty,
425                     items: new_impl_items,
426                 }))
427             }
428             ItemKind::Trait(box Trait {
429                 is_auto,
430                 unsafety,
431                 ref generics,
432                 ref bounds,
433                 ref items,
434             }) => {
435                 let (generics, (unsafety, items, bounds)) = self.lower_generics(
436                     generics,
437                     id,
438                     &mut ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
439                     |this| {
440                         let bounds = this.lower_param_bounds(
441                             bounds,
442                             &mut ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
443                         );
444                         let items = this.arena.alloc_from_iter(
445                             items.iter().map(|item| this.lower_trait_item_ref(item)),
446                         );
447                         let unsafety = this.lower_unsafety(unsafety);
448                         (unsafety, items, bounds)
449                     },
450                 );
451                 hir::ItemKind::Trait(is_auto, unsafety, generics, bounds, items)
452             }
453             ItemKind::TraitAlias(ref generics, ref bounds) => {
454                 let (generics, bounds) = self.lower_generics(
455                     generics,
456                     id,
457                     &mut ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
458                     |this| {
459                         this.lower_param_bounds(
460                             bounds,
461                             &mut ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
462                         )
463                     },
464                 );
465                 hir::ItemKind::TraitAlias(generics, bounds)
466             }
467             ItemKind::MacroDef(MacroDef { ref body, macro_rules }) => {
468                 let body = P(self.lower_mac_args(body));
469                 let macro_kind = self.resolver.decl_macro_kind(self.local_def_id(id));
470                 hir::ItemKind::Macro(ast::MacroDef { body, macro_rules }, macro_kind)
471             }
472             ItemKind::MacCall(..) => {
473                 panic!("`TyMac` should have been expanded by now")
474             }
475         }
476     }
477
478     fn lower_const_item(
479         &mut self,
480         ty: &Ty,
481         span: Span,
482         body: Option<&Expr>,
483     ) -> (&'hir hir::Ty<'hir>, hir::BodyId) {
484         let ty = self.lower_ty(ty, &mut ImplTraitContext::Disallowed(ImplTraitPosition::Type));
485         (ty, self.lower_const_body(span, body))
486     }
487
488     #[instrument(level = "debug", skip(self))]
489     fn lower_use_tree(
490         &mut self,
491         tree: &UseTree,
492         prefix: &Path,
493         id: NodeId,
494         vis_span: Span,
495         ident: &mut Ident,
496         attrs: Option<&'hir [Attribute]>,
497     ) -> hir::ItemKind<'hir> {
498         let path = &tree.prefix;
499         let segments = prefix.segments.iter().chain(path.segments.iter()).cloned().collect();
500
501         match tree.kind {
502             UseTreeKind::Simple(rename, id1, id2) => {
503                 *ident = tree.ident();
504
505                 // First, apply the prefix to the path.
506                 let mut path = Path { segments, span: path.span, tokens: None };
507
508                 // Correctly resolve `self` imports.
509                 if path.segments.len() > 1
510                     && path.segments.last().unwrap().ident.name == kw::SelfLower
511                 {
512                     let _ = path.segments.pop();
513                     if rename.is_none() {
514                         *ident = path.segments.last().unwrap().ident;
515                     }
516                 }
517
518                 let mut resolutions = self.expect_full_res_from_use(id).fuse();
519                 // We want to return *something* from this function, so hold onto the first item
520                 // for later.
521                 let ret_res = self.lower_res(resolutions.next().unwrap_or(Res::Err));
522
523                 // Here, we are looping over namespaces, if they exist for the definition
524                 // being imported. We only handle type and value namespaces because we
525                 // won't be dealing with macros in the rest of the compiler.
526                 // Essentially a single `use` which imports two names is desugared into
527                 // two imports.
528                 for new_node_id in [id1, id2] {
529                     let new_id = self.local_def_id(new_node_id);
530                     let Some(res) = resolutions.next() else {
531                         // Associate an HirId to both ids even if there is no resolution.
532                         let _old = self.children.insert(
533                             new_id,
534                             hir::MaybeOwner::NonOwner(hir::HirId::make_owner(new_id)),
535                         );
536                         debug_assert!(_old.is_none());
537                         continue;
538                     };
539                     let ident = *ident;
540                     let mut path = path.clone();
541                     for seg in &mut path.segments {
542                         seg.id = self.next_node_id();
543                     }
544                     let span = path.span;
545
546                     self.with_hir_id_owner(new_node_id, |this| {
547                         let res = this.lower_res(res);
548                         let path = this.lower_path_extra(res, &path, ParamMode::Explicit);
549                         let kind = hir::ItemKind::Use(path, hir::UseKind::Single);
550                         if let Some(attrs) = attrs {
551                             this.attrs.insert(hir::ItemLocalId::new(0), attrs);
552                         }
553
554                         let item = hir::Item {
555                             def_id: new_id,
556                             ident: this.lower_ident(ident),
557                             kind,
558                             vis_span,
559                             span: this.lower_span(span),
560                         };
561                         hir::OwnerNode::Item(this.arena.alloc(item))
562                     });
563                 }
564
565                 let path = self.lower_path_extra(ret_res, &path, ParamMode::Explicit);
566                 hir::ItemKind::Use(path, hir::UseKind::Single)
567             }
568             UseTreeKind::Glob => {
569                 let path = self.lower_path(
570                     id,
571                     &Path { segments, span: path.span, tokens: None },
572                     ParamMode::Explicit,
573                 );
574                 hir::ItemKind::Use(path, hir::UseKind::Glob)
575             }
576             UseTreeKind::Nested(ref trees) => {
577                 // Nested imports are desugared into simple imports.
578                 // So, if we start with
579                 //
580                 // ```
581                 // pub(x) use foo::{a, b};
582                 // ```
583                 //
584                 // we will create three items:
585                 //
586                 // ```
587                 // pub(x) use foo::a;
588                 // pub(x) use foo::b;
589                 // pub(x) use foo::{}; // <-- this is called the `ListStem`
590                 // ```
591                 //
592                 // The first two are produced by recursively invoking
593                 // `lower_use_tree` (and indeed there may be things
594                 // like `use foo::{a::{b, c}}` and so forth).  They
595                 // wind up being directly added to
596                 // `self.items`. However, the structure of this
597                 // function also requires us to return one item, and
598                 // for that we return the `{}` import (called the
599                 // `ListStem`).
600
601                 let prefix = Path { segments, span: prefix.span.to(path.span), tokens: None };
602
603                 // Add all the nested `PathListItem`s to the HIR.
604                 for &(ref use_tree, id) in trees {
605                     let new_hir_id = self.local_def_id(id);
606
607                     let mut prefix = prefix.clone();
608
609                     // Give the segments new node-ids since they are being cloned.
610                     for seg in &mut prefix.segments {
611                         seg.id = self.next_node_id();
612                     }
613
614                     // Each `use` import is an item and thus are owners of the
615                     // names in the path. Up to this point the nested import is
616                     // the current owner, since we want each desugared import to
617                     // own its own names, we have to adjust the owner before
618                     // lowering the rest of the import.
619                     self.with_hir_id_owner(id, |this| {
620                         let mut ident = *ident;
621
622                         let kind =
623                             this.lower_use_tree(use_tree, &prefix, id, vis_span, &mut ident, attrs);
624                         if let Some(attrs) = attrs {
625                             this.attrs.insert(hir::ItemLocalId::new(0), attrs);
626                         }
627
628                         let item = hir::Item {
629                             def_id: new_hir_id,
630                             ident: this.lower_ident(ident),
631                             kind,
632                             vis_span,
633                             span: this.lower_span(use_tree.span),
634                         };
635                         hir::OwnerNode::Item(this.arena.alloc(item))
636                     });
637                 }
638
639                 let res = self.expect_full_res_from_use(id).next().unwrap_or(Res::Err);
640                 let res = self.lower_res(res);
641                 let path = self.lower_path_extra(res, &prefix, ParamMode::Explicit);
642                 hir::ItemKind::Use(path, hir::UseKind::ListStem)
643             }
644         }
645     }
646
647     fn lower_foreign_item(&mut self, i: &ForeignItem) -> &'hir hir::ForeignItem<'hir> {
648         let hir_id = self.lower_node_id(i.id);
649         let def_id = hir_id.expect_owner();
650         self.lower_attrs(hir_id, &i.attrs);
651         let item = hir::ForeignItem {
652             def_id,
653             ident: self.lower_ident(i.ident),
654             kind: match i.kind {
655                 ForeignItemKind::Fn(box Fn { ref sig, ref generics, .. }) => {
656                     let fdec = &sig.decl;
657                     let mut itctx = ImplTraitContext::Universal;
658                     let (generics, (fn_dec, fn_args)) =
659                         self.lower_generics(generics, i.id, &mut itctx, |this| {
660                             (
661                                 // Disallow `impl Trait` in foreign items.
662                                 this.lower_fn_decl(fdec, None, FnDeclKind::ExternFn, None),
663                                 this.lower_fn_params_to_names(fdec),
664                             )
665                         });
666
667                     hir::ForeignItemKind::Fn(fn_dec, fn_args, generics)
668                 }
669                 ForeignItemKind::Static(ref t, m, _) => {
670                     let ty = self
671                         .lower_ty(t, &mut ImplTraitContext::Disallowed(ImplTraitPosition::Type));
672                     hir::ForeignItemKind::Static(ty, m)
673                 }
674                 ForeignItemKind::TyAlias(..) => hir::ForeignItemKind::Type,
675                 ForeignItemKind::MacCall(_) => panic!("macro shouldn't exist here"),
676             },
677             vis_span: self.lower_span(i.vis.span),
678             span: self.lower_span(i.span),
679         };
680         self.arena.alloc(item)
681     }
682
683     fn lower_foreign_item_ref(&mut self, i: &ForeignItem) -> hir::ForeignItemRef {
684         hir::ForeignItemRef {
685             id: hir::ForeignItemId { def_id: self.local_def_id(i.id) },
686             ident: self.lower_ident(i.ident),
687             span: self.lower_span(i.span),
688         }
689     }
690
691     fn lower_variant(&mut self, v: &Variant) -> hir::Variant<'hir> {
692         let id = self.lower_node_id(v.id);
693         self.lower_attrs(id, &v.attrs);
694         hir::Variant {
695             id,
696             data: self.lower_variant_data(id, &v.data),
697             disr_expr: v.disr_expr.as_ref().map(|e| self.lower_anon_const(e)),
698             ident: self.lower_ident(v.ident),
699             span: self.lower_span(v.span),
700         }
701     }
702
703     fn lower_variant_data(
704         &mut self,
705         parent_id: hir::HirId,
706         vdata: &VariantData,
707     ) -> hir::VariantData<'hir> {
708         match *vdata {
709             VariantData::Struct(ref fields, recovered) => hir::VariantData::Struct(
710                 self.arena
711                     .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_field_def(f))),
712                 recovered,
713             ),
714             VariantData::Tuple(ref fields, id) => {
715                 let ctor_id = self.lower_node_id(id);
716                 self.alias_attrs(ctor_id, parent_id);
717                 hir::VariantData::Tuple(
718                     self.arena.alloc_from_iter(
719                         fields.iter().enumerate().map(|f| self.lower_field_def(f)),
720                     ),
721                     ctor_id,
722                 )
723             }
724             VariantData::Unit(id) => {
725                 let ctor_id = self.lower_node_id(id);
726                 self.alias_attrs(ctor_id, parent_id);
727                 hir::VariantData::Unit(ctor_id)
728             }
729         }
730     }
731
732     fn lower_field_def(&mut self, (index, f): (usize, &FieldDef)) -> hir::FieldDef<'hir> {
733         let ty = if let TyKind::Path(ref qself, ref path) = f.ty.kind {
734             let t = self.lower_path_ty(
735                 &f.ty,
736                 qself,
737                 path,
738                 ParamMode::ExplicitNamed, // no `'_` in declarations (Issue #61124)
739                 &mut ImplTraitContext::Disallowed(ImplTraitPosition::Path),
740             );
741             self.arena.alloc(t)
742         } else {
743             self.lower_ty(&f.ty, &mut ImplTraitContext::Disallowed(ImplTraitPosition::Type))
744         };
745         let hir_id = self.lower_node_id(f.id);
746         self.lower_attrs(hir_id, &f.attrs);
747         hir::FieldDef {
748             span: self.lower_span(f.span),
749             hir_id,
750             ident: match f.ident {
751                 Some(ident) => self.lower_ident(ident),
752                 // FIXME(jseyfried): positional field hygiene.
753                 None => Ident::new(sym::integer(index), self.lower_span(f.span)),
754             },
755             vis_span: self.lower_span(f.vis.span),
756             ty,
757         }
758     }
759
760     fn lower_trait_item(&mut self, i: &AssocItem) -> &'hir hir::TraitItem<'hir> {
761         let hir_id = self.lower_node_id(i.id);
762         let trait_item_def_id = hir_id.expect_owner();
763
764         let (generics, kind, has_default) = match i.kind {
765             AssocItemKind::Const(_, ref ty, ref default) => {
766                 let ty =
767                     self.lower_ty(ty, &mut ImplTraitContext::Disallowed(ImplTraitPosition::Type));
768                 let body = default.as_ref().map(|x| self.lower_const_body(i.span, Some(x)));
769                 (hir::Generics::empty(), hir::TraitItemKind::Const(ty, body), body.is_some())
770             }
771             AssocItemKind::Fn(box Fn { ref sig, ref generics, body: None, .. }) => {
772                 let names = self.lower_fn_params_to_names(&sig.decl);
773                 let (generics, sig) =
774                     self.lower_method_sig(generics, sig, i.id, FnDeclKind::Trait, None);
775                 (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Required(names)), false)
776             }
777             AssocItemKind::Fn(box Fn { ref sig, ref generics, body: Some(ref body), .. }) => {
778                 let asyncness = sig.header.asyncness;
779                 let body_id =
780                     self.lower_maybe_async_body(i.span, &sig.decl, asyncness, Some(&body));
781                 let (generics, sig) = self.lower_method_sig(
782                     generics,
783                     sig,
784                     i.id,
785                     FnDeclKind::Trait,
786                     asyncness.opt_return_id(),
787                 );
788                 (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Provided(body_id)), true)
789             }
790             AssocItemKind::TyAlias(box TyAlias {
791                 ref generics,
792                 where_clauses,
793                 ref bounds,
794                 ref ty,
795                 ..
796             }) => {
797                 let mut generics = generics.clone();
798                 add_ty_alias_where_clause(&mut generics, where_clauses, false);
799                 let (generics, kind) = self.lower_generics(
800                     &generics,
801                     i.id,
802                     &mut ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
803                     |this| {
804                         let ty = ty.as_ref().map(|x| {
805                             this.lower_ty(
806                                 x,
807                                 &mut ImplTraitContext::Disallowed(ImplTraitPosition::Type),
808                             )
809                         });
810                         hir::TraitItemKind::Type(
811                             this.lower_param_bounds(
812                                 bounds,
813                                 &mut ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
814                             ),
815                             ty,
816                         )
817                     },
818                 );
819                 (generics, kind, ty.is_some())
820             }
821             AssocItemKind::MacCall(..) => panic!("macro item shouldn't exist at this point"),
822         };
823
824         self.lower_attrs(hir_id, &i.attrs);
825         let item = hir::TraitItem {
826             def_id: trait_item_def_id,
827             ident: self.lower_ident(i.ident),
828             generics,
829             kind,
830             span: self.lower_span(i.span),
831             defaultness: hir::Defaultness::Default { has_value: has_default },
832         };
833         self.arena.alloc(item)
834     }
835
836     fn lower_trait_item_ref(&mut self, i: &AssocItem) -> hir::TraitItemRef {
837         let kind = match &i.kind {
838             AssocItemKind::Const(..) => hir::AssocItemKind::Const,
839             AssocItemKind::TyAlias(..) => hir::AssocItemKind::Type,
840             AssocItemKind::Fn(box Fn { sig, .. }) => {
841                 hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }
842             }
843             AssocItemKind::MacCall(..) => unimplemented!(),
844         };
845         let id = hir::TraitItemId { def_id: self.local_def_id(i.id) };
846         hir::TraitItemRef {
847             id,
848             ident: self.lower_ident(i.ident),
849             span: self.lower_span(i.span),
850             kind,
851         }
852     }
853
854     /// Construct `ExprKind::Err` for the given `span`.
855     pub(crate) fn expr_err(&mut self, span: Span) -> hir::Expr<'hir> {
856         self.expr(span, hir::ExprKind::Err, AttrVec::new())
857     }
858
859     fn lower_impl_item(&mut self, i: &AssocItem) -> &'hir hir::ImplItem<'hir> {
860         // Since `default impl` is not yet implemented, this is always true in impls.
861         let has_value = true;
862         let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value);
863
864         let (generics, kind) = match &i.kind {
865             AssocItemKind::Const(_, ty, expr) => {
866                 let ty =
867                     self.lower_ty(ty, &mut ImplTraitContext::Disallowed(ImplTraitPosition::Type));
868                 (
869                     hir::Generics::empty(),
870                     hir::ImplItemKind::Const(ty, self.lower_const_body(i.span, expr.as_deref())),
871                 )
872             }
873             AssocItemKind::Fn(box Fn { sig, generics, body, .. }) => {
874                 self.current_item = Some(i.span);
875                 let asyncness = sig.header.asyncness;
876                 let body_id =
877                     self.lower_maybe_async_body(i.span, &sig.decl, asyncness, body.as_deref());
878                 let (generics, sig) = self.lower_method_sig(
879                     generics,
880                     sig,
881                     i.id,
882                     if self.is_in_trait_impl { FnDeclKind::Impl } else { FnDeclKind::Inherent },
883                     asyncness.opt_return_id(),
884                 );
885
886                 (generics, hir::ImplItemKind::Fn(sig, body_id))
887             }
888             AssocItemKind::TyAlias(box TyAlias { generics, where_clauses, ty, .. }) => {
889                 let mut generics = generics.clone();
890                 add_ty_alias_where_clause(&mut generics, *where_clauses, false);
891                 self.lower_generics(
892                     &generics,
893                     i.id,
894                     &mut ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
895                     |this| match ty {
896                         None => {
897                             let ty = this.arena.alloc(this.ty(i.span, hir::TyKind::Err));
898                             hir::ImplItemKind::TyAlias(ty)
899                         }
900                         Some(ty) => {
901                             let ty = this.lower_ty(ty, &mut ImplTraitContext::TypeAliasesOpaqueTy);
902                             hir::ImplItemKind::TyAlias(ty)
903                         }
904                     },
905                 )
906             }
907             AssocItemKind::MacCall(..) => panic!("`TyMac` should have been expanded by now"),
908         };
909
910         let hir_id = self.lower_node_id(i.id);
911         self.lower_attrs(hir_id, &i.attrs);
912         let item = hir::ImplItem {
913             def_id: hir_id.expect_owner(),
914             ident: self.lower_ident(i.ident),
915             generics,
916             kind,
917             vis_span: self.lower_span(i.vis.span),
918             span: self.lower_span(i.span),
919             defaultness,
920         };
921         self.arena.alloc(item)
922     }
923
924     fn lower_impl_item_ref(&mut self, i: &AssocItem) -> hir::ImplItemRef {
925         hir::ImplItemRef {
926             id: hir::ImplItemId { def_id: self.local_def_id(i.id) },
927             ident: self.lower_ident(i.ident),
928             span: self.lower_span(i.span),
929             kind: match &i.kind {
930                 AssocItemKind::Const(..) => hir::AssocItemKind::Const,
931                 AssocItemKind::TyAlias(..) => hir::AssocItemKind::Type,
932                 AssocItemKind::Fn(box Fn { sig, .. }) => {
933                     hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }
934                 }
935                 AssocItemKind::MacCall(..) => unimplemented!(),
936             },
937             trait_item_def_id: self.resolver.get_partial_res(i.id).map(|r| r.base_res().def_id()),
938         }
939     }
940
941     fn lower_defaultness(
942         &self,
943         d: Defaultness,
944         has_value: bool,
945     ) -> (hir::Defaultness, Option<Span>) {
946         match d {
947             Defaultness::Default(sp) => {
948                 (hir::Defaultness::Default { has_value }, Some(self.lower_span(sp)))
949             }
950             Defaultness::Final => {
951                 assert!(has_value);
952                 (hir::Defaultness::Final, None)
953             }
954         }
955     }
956
957     fn record_body(
958         &mut self,
959         params: &'hir [hir::Param<'hir>],
960         value: hir::Expr<'hir>,
961     ) -> hir::BodyId {
962         let body = hir::Body {
963             generator_kind: self.generator_kind,
964             params,
965             value: self.arena.alloc(value),
966         };
967         let id = body.id();
968         debug_assert_eq!(id.hir_id.owner, self.current_hir_id_owner);
969         self.bodies.push((id.hir_id.local_id, self.arena.alloc(body)));
970         id
971     }
972
973     pub(super) fn lower_body(
974         &mut self,
975         f: impl FnOnce(&mut Self) -> (&'hir [hir::Param<'hir>], hir::Expr<'hir>),
976     ) -> hir::BodyId {
977         let prev_gen_kind = self.generator_kind.take();
978         let task_context = self.task_context.take();
979         let (parameters, result) = f(self);
980         let body_id = self.record_body(parameters, result);
981         self.task_context = task_context;
982         self.generator_kind = prev_gen_kind;
983         body_id
984     }
985
986     fn lower_param(&mut self, param: &Param) -> hir::Param<'hir> {
987         let hir_id = self.lower_node_id(param.id);
988         self.lower_attrs(hir_id, &param.attrs);
989         hir::Param {
990             hir_id,
991             pat: self.lower_pat(&param.pat),
992             ty_span: self.lower_span(param.ty.span),
993             span: self.lower_span(param.span),
994         }
995     }
996
997     pub(super) fn lower_fn_body(
998         &mut self,
999         decl: &FnDecl,
1000         body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
1001     ) -> hir::BodyId {
1002         self.lower_body(|this| {
1003             (
1004                 this.arena.alloc_from_iter(decl.inputs.iter().map(|x| this.lower_param(x))),
1005                 body(this),
1006             )
1007         })
1008     }
1009
1010     fn lower_fn_body_block(
1011         &mut self,
1012         span: Span,
1013         decl: &FnDecl,
1014         body: Option<&Block>,
1015     ) -> hir::BodyId {
1016         self.lower_fn_body(decl, |this| this.lower_block_expr_opt(span, body))
1017     }
1018
1019     fn lower_block_expr_opt(&mut self, span: Span, block: Option<&Block>) -> hir::Expr<'hir> {
1020         match block {
1021             Some(block) => self.lower_block_expr(block),
1022             None => self.expr_err(span),
1023         }
1024     }
1025
1026     pub(super) fn lower_const_body(&mut self, span: Span, expr: Option<&Expr>) -> hir::BodyId {
1027         self.lower_body(|this| {
1028             (
1029                 &[],
1030                 match expr {
1031                     Some(expr) => this.lower_expr_mut(expr),
1032                     None => this.expr_err(span),
1033                 },
1034             )
1035         })
1036     }
1037
1038     fn lower_maybe_async_body(
1039         &mut self,
1040         span: Span,
1041         decl: &FnDecl,
1042         asyncness: Async,
1043         body: Option<&Block>,
1044     ) -> hir::BodyId {
1045         let closure_id = match asyncness {
1046             Async::Yes { closure_id, .. } => closure_id,
1047             Async::No => return self.lower_fn_body_block(span, decl, body),
1048         };
1049
1050         self.lower_body(|this| {
1051             let mut parameters: Vec<hir::Param<'_>> = Vec::new();
1052             let mut statements: Vec<hir::Stmt<'_>> = Vec::new();
1053
1054             // Async function parameters are lowered into the closure body so that they are
1055             // captured and so that the drop order matches the equivalent non-async functions.
1056             //
1057             // from:
1058             //
1059             //     async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
1060             //         <body>
1061             //     }
1062             //
1063             // into:
1064             //
1065             //     fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
1066             //       async move {
1067             //         let __arg2 = __arg2;
1068             //         let <pattern> = __arg2;
1069             //         let __arg1 = __arg1;
1070             //         let <pattern> = __arg1;
1071             //         let __arg0 = __arg0;
1072             //         let <pattern> = __arg0;
1073             //         drop-temps { <body> } // see comments later in fn for details
1074             //       }
1075             //     }
1076             //
1077             // If `<pattern>` is a simple ident, then it is lowered to a single
1078             // `let <pattern> = <pattern>;` statement as an optimization.
1079             //
1080             // Note that the body is embedded in `drop-temps`; an
1081             // equivalent desugaring would be `return { <body>
1082             // };`. The key point is that we wish to drop all the
1083             // let-bound variables and temporaries created in the body
1084             // (and its tail expression!) before we drop the
1085             // parameters (c.f. rust-lang/rust#64512).
1086             for (index, parameter) in decl.inputs.iter().enumerate() {
1087                 let parameter = this.lower_param(parameter);
1088                 let span = parameter.pat.span;
1089
1090                 // Check if this is a binding pattern, if so, we can optimize and avoid adding a
1091                 // `let <pat> = __argN;` statement. In this case, we do not rename the parameter.
1092                 let (ident, is_simple_parameter) = match parameter.pat.kind {
1093                     hir::PatKind::Binding(hir::BindingAnnotation(ByRef::No, _), _, ident, _) => {
1094                         (ident, true)
1095                     }
1096                     // For `ref mut` or wildcard arguments, we can't reuse the binding, but
1097                     // we can keep the same name for the parameter.
1098                     // This lets rustdoc render it correctly in documentation.
1099                     hir::PatKind::Binding(_, _, ident, _) => (ident, false),
1100                     hir::PatKind::Wild => {
1101                         (Ident::with_dummy_span(rustc_span::symbol::kw::Underscore), false)
1102                     }
1103                     _ => {
1104                         // Replace the ident for bindings that aren't simple.
1105                         let name = format!("__arg{}", index);
1106                         let ident = Ident::from_str(&name);
1107
1108                         (ident, false)
1109                     }
1110                 };
1111
1112                 let desugared_span = this.mark_span_with_reason(DesugaringKind::Async, span, None);
1113
1114                 // Construct a parameter representing `__argN: <ty>` to replace the parameter of the
1115                 // async function.
1116                 //
1117                 // If this is the simple case, this parameter will end up being the same as the
1118                 // original parameter, but with a different pattern id.
1119                 let stmt_attrs = this.attrs.get(&parameter.hir_id.local_id).copied();
1120                 let (new_parameter_pat, new_parameter_id) = this.pat_ident(desugared_span, ident);
1121                 let new_parameter = hir::Param {
1122                     hir_id: parameter.hir_id,
1123                     pat: new_parameter_pat,
1124                     ty_span: this.lower_span(parameter.ty_span),
1125                     span: this.lower_span(parameter.span),
1126                 };
1127
1128                 if is_simple_parameter {
1129                     // If this is the simple case, then we only insert one statement that is
1130                     // `let <pat> = <pat>;`. We re-use the original argument's pattern so that
1131                     // `HirId`s are densely assigned.
1132                     let expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1133                     let stmt = this.stmt_let_pat(
1134                         stmt_attrs,
1135                         desugared_span,
1136                         Some(expr),
1137                         parameter.pat,
1138                         hir::LocalSource::AsyncFn,
1139                     );
1140                     statements.push(stmt);
1141                 } else {
1142                     // If this is not the simple case, then we construct two statements:
1143                     //
1144                     // ```
1145                     // let __argN = __argN;
1146                     // let <pat> = __argN;
1147                     // ```
1148                     //
1149                     // The first statement moves the parameter into the closure and thus ensures
1150                     // that the drop order is correct.
1151                     //
1152                     // The second statement creates the bindings that the user wrote.
1153
1154                     // Construct the `let mut __argN = __argN;` statement. It must be a mut binding
1155                     // because the user may have specified a `ref mut` binding in the next
1156                     // statement.
1157                     let (move_pat, move_id) = this.pat_ident_binding_mode(
1158                         desugared_span,
1159                         ident,
1160                         hir::BindingAnnotation::MUT,
1161                     );
1162                     let move_expr = this.expr_ident(desugared_span, ident, new_parameter_id);
1163                     let move_stmt = this.stmt_let_pat(
1164                         None,
1165                         desugared_span,
1166                         Some(move_expr),
1167                         move_pat,
1168                         hir::LocalSource::AsyncFn,
1169                     );
1170
1171                     // Construct the `let <pat> = __argN;` statement. We re-use the original
1172                     // parameter's pattern so that `HirId`s are densely assigned.
1173                     let pattern_expr = this.expr_ident(desugared_span, ident, move_id);
1174                     let pattern_stmt = this.stmt_let_pat(
1175                         stmt_attrs,
1176                         desugared_span,
1177                         Some(pattern_expr),
1178                         parameter.pat,
1179                         hir::LocalSource::AsyncFn,
1180                     );
1181
1182                     statements.push(move_stmt);
1183                     statements.push(pattern_stmt);
1184                 };
1185
1186                 parameters.push(new_parameter);
1187             }
1188
1189             let body_span = body.map_or(span, |b| b.span);
1190             let async_expr = this.make_async_expr(
1191                 CaptureBy::Value,
1192                 closure_id,
1193                 None,
1194                 body_span,
1195                 hir::AsyncGeneratorKind::Fn,
1196                 |this| {
1197                     // Create a block from the user's function body:
1198                     let user_body = this.lower_block_expr_opt(body_span, body);
1199
1200                     // Transform into `drop-temps { <user-body> }`, an expression:
1201                     let desugared_span =
1202                         this.mark_span_with_reason(DesugaringKind::Async, user_body.span, None);
1203                     let user_body = this.expr_drop_temps(
1204                         desugared_span,
1205                         this.arena.alloc(user_body),
1206                         AttrVec::new(),
1207                     );
1208
1209                     // As noted above, create the final block like
1210                     //
1211                     // ```
1212                     // {
1213                     //   let $param_pattern = $raw_param;
1214                     //   ...
1215                     //   drop-temps { <user-body> }
1216                     // }
1217                     // ```
1218                     let body = this.block_all(
1219                         desugared_span,
1220                         this.arena.alloc_from_iter(statements),
1221                         Some(user_body),
1222                     );
1223
1224                     this.expr_block(body, AttrVec::new())
1225                 },
1226             );
1227
1228             (
1229                 this.arena.alloc_from_iter(parameters),
1230                 this.expr(body_span, async_expr, AttrVec::new()),
1231             )
1232         })
1233     }
1234
1235     fn lower_method_sig(
1236         &mut self,
1237         generics: &Generics,
1238         sig: &FnSig,
1239         id: NodeId,
1240         kind: FnDeclKind,
1241         is_async: Option<NodeId>,
1242     ) -> (&'hir hir::Generics<'hir>, hir::FnSig<'hir>) {
1243         let header = self.lower_fn_header(sig.header);
1244         let mut itctx = ImplTraitContext::Universal;
1245         let (generics, decl) = self.lower_generics(generics, id, &mut itctx, |this| {
1246             this.lower_fn_decl(&sig.decl, Some(id), kind, is_async)
1247         });
1248         (generics, hir::FnSig { header, decl, span: self.lower_span(sig.span) })
1249     }
1250
1251     fn lower_fn_header(&mut self, h: FnHeader) -> hir::FnHeader {
1252         hir::FnHeader {
1253             unsafety: self.lower_unsafety(h.unsafety),
1254             asyncness: self.lower_asyncness(h.asyncness),
1255             constness: self.lower_constness(h.constness),
1256             abi: self.lower_extern(h.ext),
1257         }
1258     }
1259
1260     pub(super) fn lower_abi(&mut self, abi: StrLit) -> abi::Abi {
1261         abi::lookup(abi.symbol_unescaped.as_str()).unwrap_or_else(|| {
1262             self.error_on_invalid_abi(abi);
1263             abi::Abi::Rust
1264         })
1265     }
1266
1267     pub(super) fn lower_extern(&mut self, ext: Extern) -> abi::Abi {
1268         match ext {
1269             Extern::None => abi::Abi::Rust,
1270             Extern::Implicit(_) => abi::Abi::FALLBACK,
1271             Extern::Explicit(abi, _) => self.lower_abi(abi),
1272         }
1273     }
1274
1275     fn error_on_invalid_abi(&self, abi: StrLit) {
1276         self.tcx.sess.emit_err(InvalidAbi {
1277             span: abi.span,
1278             abi: abi.symbol,
1279             valid_abis: abi::all_names().join(", "),
1280         });
1281     }
1282
1283     fn lower_asyncness(&mut self, a: Async) -> hir::IsAsync {
1284         match a {
1285             Async::Yes { .. } => hir::IsAsync::Async,
1286             Async::No => hir::IsAsync::NotAsync,
1287         }
1288     }
1289
1290     fn lower_constness(&mut self, c: Const) -> hir::Constness {
1291         match c {
1292             Const::Yes(_) => hir::Constness::Const,
1293             Const::No => hir::Constness::NotConst,
1294         }
1295     }
1296
1297     pub(super) fn lower_unsafety(&mut self, u: Unsafe) -> hir::Unsafety {
1298         match u {
1299             Unsafe::Yes(_) => hir::Unsafety::Unsafe,
1300             Unsafe::No => hir::Unsafety::Normal,
1301         }
1302     }
1303
1304     /// Return the pair of the lowered `generics` as `hir::Generics` and the evaluation of `f` with
1305     /// the carried impl trait definitions and bounds.
1306     #[instrument(level = "debug", skip(self, f))]
1307     fn lower_generics<T>(
1308         &mut self,
1309         generics: &Generics,
1310         parent_node_id: NodeId,
1311         itctx: &mut ImplTraitContext,
1312         f: impl FnOnce(&mut Self) -> T,
1313     ) -> (&'hir hir::Generics<'hir>, T) {
1314         debug_assert!(self.impl_trait_defs.is_empty());
1315         debug_assert!(self.impl_trait_bounds.is_empty());
1316
1317         // Error if `?Trait` bounds in where clauses don't refer directly to type parameters.
1318         // Note: we used to clone these bounds directly onto the type parameter (and avoid lowering
1319         // these into hir when we lower thee where clauses), but this makes it quite difficult to
1320         // keep track of the Span info. Now, `add_implicitly_sized` in `AstConv` checks both param bounds and
1321         // where clauses for `?Sized`.
1322         for pred in &generics.where_clause.predicates {
1323             let WherePredicate::BoundPredicate(ref bound_pred) = *pred else {
1324                 continue;
1325             };
1326             let compute_is_param = || {
1327                 // Check if the where clause type is a plain type parameter.
1328                 match self
1329                     .resolver
1330                     .get_partial_res(bound_pred.bounded_ty.id)
1331                     .map(|d| (d.base_res(), d.unresolved_segments()))
1332                 {
1333                     Some((Res::Def(DefKind::TyParam, def_id), 0))
1334                         if bound_pred.bound_generic_params.is_empty() =>
1335                     {
1336                         generics
1337                             .params
1338                             .iter()
1339                             .any(|p| def_id == self.local_def_id(p.id).to_def_id())
1340                     }
1341                     // Either the `bounded_ty` is not a plain type parameter, or
1342                     // it's not found in the generic type parameters list.
1343                     _ => false,
1344                 }
1345             };
1346             // We only need to compute this once per `WherePredicate`, but don't
1347             // need to compute this at all unless there is a Maybe bound.
1348             let mut is_param: Option<bool> = None;
1349             for bound in &bound_pred.bounds {
1350                 if !matches!(*bound, GenericBound::Trait(_, TraitBoundModifier::Maybe)) {
1351                     continue;
1352                 }
1353                 let is_param = *is_param.get_or_insert_with(compute_is_param);
1354                 if !is_param {
1355                     self.tcx.sess.emit_err(MisplacedRelaxTraitBound { span: bound.span() });
1356                 }
1357             }
1358         }
1359
1360         let mut predicates: SmallVec<[hir::WherePredicate<'hir>; 4]> = SmallVec::new();
1361         predicates.extend(generics.params.iter().filter_map(|param| {
1362             self.lower_generic_bound_predicate(
1363                 param.ident,
1364                 param.id,
1365                 &param.kind,
1366                 &param.bounds,
1367                 itctx,
1368                 PredicateOrigin::GenericParam,
1369             )
1370         }));
1371         predicates.extend(
1372             generics
1373                 .where_clause
1374                 .predicates
1375                 .iter()
1376                 .map(|predicate| self.lower_where_predicate(predicate)),
1377         );
1378
1379         let mut params: SmallVec<[hir::GenericParam<'hir>; 4]> =
1380             self.lower_generic_params_mut(&generics.params).collect();
1381
1382         // Introduce extra lifetimes if late resolution tells us to.
1383         let extra_lifetimes = self.resolver.take_extra_lifetime_params(parent_node_id);
1384         params.extend(extra_lifetimes.into_iter().filter_map(|(ident, node_id, res)| {
1385             self.lifetime_res_to_generic_param(ident, node_id, res)
1386         }));
1387
1388         let has_where_clause_predicates = !generics.where_clause.predicates.is_empty();
1389         let where_clause_span = self.lower_span(generics.where_clause.span);
1390         let span = self.lower_span(generics.span);
1391         let res = f(self);
1392
1393         let impl_trait_defs = std::mem::take(&mut self.impl_trait_defs);
1394         params.extend(impl_trait_defs.into_iter());
1395
1396         let impl_trait_bounds = std::mem::take(&mut self.impl_trait_bounds);
1397         predicates.extend(impl_trait_bounds.into_iter());
1398
1399         let lowered_generics = self.arena.alloc(hir::Generics {
1400             params: self.arena.alloc_from_iter(params),
1401             predicates: self.arena.alloc_from_iter(predicates),
1402             has_where_clause_predicates,
1403             where_clause_span,
1404             span,
1405         });
1406
1407         (lowered_generics, res)
1408     }
1409
1410     pub(super) fn lower_generic_bound_predicate(
1411         &mut self,
1412         ident: Ident,
1413         id: NodeId,
1414         kind: &GenericParamKind,
1415         bounds: &[GenericBound],
1416         itctx: &mut ImplTraitContext,
1417         origin: PredicateOrigin,
1418     ) -> Option<hir::WherePredicate<'hir>> {
1419         // Do not create a clause if we do not have anything inside it.
1420         if bounds.is_empty() {
1421             return None;
1422         }
1423
1424         let bounds = self.lower_param_bounds(bounds, itctx);
1425
1426         let ident = self.lower_ident(ident);
1427         let param_span = ident.span;
1428         let span = bounds
1429             .iter()
1430             .fold(Some(param_span.shrink_to_hi()), |span: Option<Span>, bound| {
1431                 let bound_span = bound.span();
1432                 // We include bounds that come from a `#[derive(_)]` but point at the user's code,
1433                 // as we use this method to get a span appropriate for suggestions.
1434                 if !bound_span.can_be_used_for_suggestions() {
1435                     None
1436                 } else if let Some(span) = span {
1437                     Some(span.to(bound_span))
1438                 } else {
1439                     Some(bound_span)
1440                 }
1441             })
1442             .unwrap_or(param_span.shrink_to_hi());
1443         match kind {
1444             GenericParamKind::Const { .. } => None,
1445             GenericParamKind::Type { .. } => {
1446                 let def_id = self.local_def_id(id).to_def_id();
1447                 let hir_id = self.next_id();
1448                 let res = Res::Def(DefKind::TyParam, def_id);
1449                 let ty_path = self.arena.alloc(hir::Path {
1450                     span: param_span,
1451                     res,
1452                     segments: self
1453                         .arena
1454                         .alloc_from_iter([hir::PathSegment::new(ident, hir_id, res)]),
1455                 });
1456                 let ty_id = self.next_id();
1457                 let bounded_ty =
1458                     self.ty_path(ty_id, param_span, hir::QPath::Resolved(None, ty_path));
1459                 Some(hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1460                     bounded_ty: self.arena.alloc(bounded_ty),
1461                     bounds,
1462                     span,
1463                     bound_generic_params: &[],
1464                     origin,
1465                 }))
1466             }
1467             GenericParamKind::Lifetime => {
1468                 let ident_span = self.lower_span(ident.span);
1469                 let ident = self.lower_ident(ident);
1470                 let lt_id = self.next_node_id();
1471                 let lifetime = self.new_named_lifetime(id, lt_id, ident_span, ident);
1472                 Some(hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1473                     lifetime,
1474                     span,
1475                     bounds,
1476                     in_where_clause: false,
1477                 }))
1478             }
1479         }
1480     }
1481
1482     fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate<'hir> {
1483         match *pred {
1484             WherePredicate::BoundPredicate(WhereBoundPredicate {
1485                 ref bound_generic_params,
1486                 ref bounded_ty,
1487                 ref bounds,
1488                 span,
1489             }) => hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate {
1490                 bound_generic_params: self.lower_generic_params(bound_generic_params),
1491                 bounded_ty: self.lower_ty(
1492                     bounded_ty,
1493                     &mut ImplTraitContext::Disallowed(ImplTraitPosition::Type),
1494                 ),
1495                 bounds: self.arena.alloc_from_iter(bounds.iter().map(|bound| {
1496                     self.lower_param_bound(
1497                         bound,
1498                         &mut ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
1499                     )
1500                 })),
1501                 span: self.lower_span(span),
1502                 origin: PredicateOrigin::WhereClause,
1503             }),
1504             WherePredicate::RegionPredicate(WhereRegionPredicate {
1505                 ref lifetime,
1506                 ref bounds,
1507                 span,
1508             }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate {
1509                 span: self.lower_span(span),
1510                 lifetime: self.lower_lifetime(lifetime),
1511                 bounds: self.lower_param_bounds(
1512                     bounds,
1513                     &mut ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
1514                 ),
1515                 in_where_clause: true,
1516             }),
1517             WherePredicate::EqPredicate(WhereEqPredicate { ref lhs_ty, ref rhs_ty, span }) => {
1518                 hir::WherePredicate::EqPredicate(hir::WhereEqPredicate {
1519                     lhs_ty: self.lower_ty(
1520                         lhs_ty,
1521                         &mut ImplTraitContext::Disallowed(ImplTraitPosition::Type),
1522                     ),
1523                     rhs_ty: self.lower_ty(
1524                         rhs_ty,
1525                         &mut ImplTraitContext::Disallowed(ImplTraitPosition::Type),
1526                     ),
1527                     span: self.lower_span(span),
1528                 })
1529             }
1530         }
1531     }
1532 }