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