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