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