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