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