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