rustc_ast_lowering/
item.rs

1use rustc_abi::ExternAbi;
2use rustc_ast::visit::AssocCtxt;
3use rustc_ast::*;
4use rustc_errors::{E0570, ErrorGuaranteed, struct_span_code_err};
5use rustc_hir::attrs::{AttributeKind, EiiDecl};
6use rustc_hir::def::{DefKind, PerNS, Res};
7use rustc_hir::def_id::{CRATE_DEF_ID, LocalDefId};
8use rustc_hir::{
9    self as hir, HirId, ImplItemImplKind, LifetimeSource, PredicateOrigin, Target, find_attr,
10};
11use rustc_index::{IndexSlice, IndexVec};
12use rustc_middle::span_bug;
13use rustc_middle::ty::{ResolverAstLowering, TyCtxt};
14use rustc_span::def_id::DefId;
15use rustc_span::edit_distance::find_best_match_for_name;
16use rustc_span::{DUMMY_SP, DesugaringKind, Ident, Span, Symbol, kw, sym};
17use smallvec::{SmallVec, smallvec};
18use thin_vec::ThinVec;
19use tracing::instrument;
20
21use super::errors::{InvalidAbi, InvalidAbiSuggestion, TupleStructWithDefault, UnionWithDefault};
22use super::stability::{enabled_names, gate_unstable_abi};
23use super::{
24    AstOwner, FnDeclKind, ImplTraitContext, ImplTraitPosition, LoweringContext, ParamMode,
25    RelaxedBoundForbiddenReason, RelaxedBoundPolicy, ResolverAstLoweringExt,
26};
27
28pub(super) struct ItemLowerer<'a, 'hir> {
29    pub(super) tcx: TyCtxt<'hir>,
30    pub(super) resolver: &'a mut ResolverAstLowering,
31    pub(super) ast_index: &'a IndexSlice<LocalDefId, AstOwner<'a>>,
32    pub(super) owners: &'a mut IndexVec<LocalDefId, hir::MaybeOwner<'hir>>,
33}
34
35/// When we have a ty alias we *may* have two where clauses. To give the best diagnostics, we set the span
36/// to the where clause that is preferred, if it exists. Otherwise, it sets the span to the other where
37/// clause if it exists.
38fn add_ty_alias_where_clause(
39    generics: &mut ast::Generics,
40    after_where_clause: &ast::WhereClause,
41    prefer_first: bool,
42) {
43    generics.where_clause.predicates.extend_from_slice(&after_where_clause.predicates);
44
45    let mut before = (generics.where_clause.has_where_token, generics.where_clause.span);
46    let mut after = (after_where_clause.has_where_token, after_where_clause.span);
47    if !prefer_first {
48        (before, after) = (after, before);
49    }
50    (generics.where_clause.has_where_token, generics.where_clause.span) =
51        if before.0 || !after.0 { before } else { after };
52}
53
54impl<'a, 'hir> ItemLowerer<'a, 'hir> {
55    fn with_lctx(
56        &mut self,
57        owner: NodeId,
58        f: impl FnOnce(&mut LoweringContext<'_, 'hir>) -> hir::OwnerNode<'hir>,
59    ) {
60        let mut lctx = LoweringContext::new(self.tcx, self.resolver);
61        lctx.with_hir_id_owner(owner, |lctx| f(lctx));
62
63        for (def_id, info) in lctx.children {
64            let owner = self.owners.ensure_contains_elem(def_id, || hir::MaybeOwner::Phantom);
65            assert!(
66                matches!(owner, hir::MaybeOwner::Phantom),
67                "duplicate copy of {def_id:?} in lctx.children"
68            );
69            *owner = info;
70        }
71    }
72
73    pub(super) fn lower_node(&mut self, def_id: LocalDefId) {
74        let owner = self.owners.ensure_contains_elem(def_id, || hir::MaybeOwner::Phantom);
75        if let hir::MaybeOwner::Phantom = owner {
76            let node = self.ast_index[def_id];
77            match node {
78                AstOwner::NonOwner => {}
79                AstOwner::Crate(c) => {
80                    assert_eq!(self.resolver.node_id_to_def_id[&CRATE_NODE_ID], CRATE_DEF_ID);
81                    self.with_lctx(CRATE_NODE_ID, |lctx| {
82                        let module = lctx.lower_mod(&c.items, &c.spans);
83                        // FIXME(jdonszelman): is dummy span ever a problem here?
84                        lctx.lower_attrs(hir::CRATE_HIR_ID, &c.attrs, DUMMY_SP, Target::Crate);
85                        hir::OwnerNode::Crate(module)
86                    })
87                }
88                AstOwner::Item(item) => {
89                    self.with_lctx(item.id, |lctx| hir::OwnerNode::Item(lctx.lower_item(item)))
90                }
91                AstOwner::AssocItem(item, ctxt) => {
92                    self.with_lctx(item.id, |lctx| lctx.lower_assoc_item(item, ctxt))
93                }
94                AstOwner::ForeignItem(item) => self.with_lctx(item.id, |lctx| {
95                    hir::OwnerNode::ForeignItem(lctx.lower_foreign_item(item))
96                }),
97            }
98        }
99    }
100}
101
102impl<'hir> LoweringContext<'_, 'hir> {
103    pub(super) fn lower_mod(
104        &mut self,
105        items: &[Box<Item>],
106        spans: &ModSpans,
107    ) -> &'hir hir::Mod<'hir> {
108        self.arena.alloc(hir::Mod {
109            spans: hir::ModSpans {
110                inner_span: self.lower_span(spans.inner_span),
111                inject_use_span: self.lower_span(spans.inject_use_span),
112            },
113            item_ids: self.arena.alloc_from_iter(items.iter().flat_map(|x| self.lower_item_ref(x))),
114        })
115    }
116
117    pub(super) fn lower_item_ref(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> {
118        let mut node_ids = smallvec![hir::ItemId { owner_id: self.owner_id(i.id) }];
119        if let ItemKind::Use(use_tree) = &i.kind {
120            self.lower_item_id_use_tree(use_tree, &mut node_ids);
121        }
122        node_ids
123    }
124
125    fn lower_item_id_use_tree(&mut self, tree: &UseTree, vec: &mut SmallVec<[hir::ItemId; 1]>) {
126        match &tree.kind {
127            UseTreeKind::Nested { items, .. } => {
128                for &(ref nested, id) in items {
129                    vec.push(hir::ItemId { owner_id: self.owner_id(id) });
130                    self.lower_item_id_use_tree(nested, vec);
131                }
132            }
133            UseTreeKind::Simple(..) | UseTreeKind::Glob => {}
134        }
135    }
136
137    fn generate_extra_attrs_for_item_kind(
138        &mut self,
139        id: NodeId,
140        i: &ItemKind,
141    ) -> Vec<hir::Attribute> {
142        match i {
143            ItemKind::Fn(box Fn { eii_impls, .. }) if eii_impls.is_empty() => Vec::new(),
144            ItemKind::Fn(box Fn { eii_impls, .. }) => {
145                vec![hir::Attribute::Parsed(AttributeKind::EiiImpls(
146                    eii_impls
147                        .iter()
148                        .flat_map(
149                            |EiiImpl {
150                                 node_id,
151                                 eii_macro_path,
152                                 impl_safety,
153                                 span,
154                                 inner_span,
155                                 is_default,
156                             }| {
157                                self.lower_path_simple_eii(*node_id, eii_macro_path).map(|did| {
158                                    hir::attrs::EiiImpl {
159                                        eii_macro: did,
160                                        span: self.lower_span(*span),
161                                        inner_span: self.lower_span(*inner_span),
162                                        impl_marked_unsafe: self
163                                            .lower_safety(*impl_safety, hir::Safety::Safe)
164                                            .is_unsafe(),
165                                        is_default: *is_default,
166                                    }
167                                })
168                            },
169                        )
170                        .collect(),
171                ))]
172            }
173            ItemKind::MacroDef(
174                _,
175                MacroDef {
176                    eii_extern_target: Some(EiiExternTarget { extern_item_path, impl_unsafe, span }),
177                    ..
178                },
179            ) => self
180                .lower_path_simple_eii(id, extern_item_path)
181                .map(|did| {
182                    vec![hir::Attribute::Parsed(AttributeKind::EiiExternTarget(EiiDecl {
183                        eii_extern_target: did,
184                        impl_unsafe: *impl_unsafe,
185                        span: self.lower_span(*span),
186                    }))]
187                })
188                .unwrap_or_default(),
189            ItemKind::ExternCrate(..)
190            | ItemKind::Use(..)
191            | ItemKind::Static(..)
192            | ItemKind::Const(..)
193            | ItemKind::Mod(..)
194            | ItemKind::ForeignMod(..)
195            | ItemKind::GlobalAsm(..)
196            | ItemKind::TyAlias(..)
197            | ItemKind::Enum(..)
198            | ItemKind::Struct(..)
199            | ItemKind::Union(..)
200            | ItemKind::Trait(..)
201            | ItemKind::TraitAlias(..)
202            | ItemKind::Impl(..)
203            | ItemKind::MacCall(..)
204            | ItemKind::MacroDef(..)
205            | ItemKind::Delegation(..)
206            | ItemKind::DelegationMac(..) => Vec::new(),
207        }
208    }
209
210    fn lower_item(&mut self, i: &Item) -> &'hir hir::Item<'hir> {
211        let vis_span = self.lower_span(i.vis.span);
212        let hir_id = hir::HirId::make_owner(self.current_hir_id_owner.def_id);
213
214        let extra_hir_attributes = self.generate_extra_attrs_for_item_kind(i.id, &i.kind);
215        let attrs = self.lower_attrs_with_extra(
216            hir_id,
217            &i.attrs,
218            i.span,
219            Target::from_ast_item(i),
220            &extra_hir_attributes,
221        );
222
223        let kind = self.lower_item_kind(i.span, i.id, hir_id, attrs, vis_span, &i.kind);
224        let item = hir::Item {
225            owner_id: hir_id.expect_owner(),
226            kind,
227            vis_span,
228            span: self.lower_span(i.span),
229            has_delayed_lints: !self.delayed_lints.is_empty(),
230            eii: find_attr!(
231                attrs,
232                AttributeKind::EiiImpls(..) | AttributeKind::EiiExternTarget(..)
233            ),
234        };
235        self.arena.alloc(item)
236    }
237
238    fn lower_item_kind(
239        &mut self,
240        span: Span,
241        id: NodeId,
242        hir_id: hir::HirId,
243        attrs: &'hir [hir::Attribute],
244        vis_span: Span,
245        i: &ItemKind,
246    ) -> hir::ItemKind<'hir> {
247        match i {
248            ItemKind::ExternCrate(orig_name, ident) => {
249                let ident = self.lower_ident(*ident);
250                hir::ItemKind::ExternCrate(*orig_name, ident)
251            }
252            ItemKind::Use(use_tree) => {
253                // Start with an empty prefix.
254                let prefix = Path { segments: ThinVec::new(), span: use_tree.span, tokens: None };
255
256                self.lower_use_tree(use_tree, &prefix, id, vis_span, attrs)
257            }
258            ItemKind::Static(box ast::StaticItem {
259                ident,
260                ty,
261                safety: _,
262                mutability: m,
263                expr: e,
264                define_opaque,
265            }) => {
266                let ident = self.lower_ident(*ident);
267                let ty = self
268                    .lower_ty_alloc(ty, ImplTraitContext::Disallowed(ImplTraitPosition::StaticTy));
269                let body_id = self.lower_const_body(span, e.as_deref());
270                self.lower_define_opaque(hir_id, define_opaque);
271                hir::ItemKind::Static(*m, ident, ty, body_id)
272            }
273            ItemKind::Const(box ast::ConstItem {
274                ident, generics, ty, rhs, define_opaque, ..
275            }) => {
276                let ident = self.lower_ident(*ident);
277                let (generics, (ty, rhs)) = self.lower_generics(
278                    generics,
279                    id,
280                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
281                    |this| {
282                        let ty = this.lower_ty_alloc(
283                            ty,
284                            ImplTraitContext::Disallowed(ImplTraitPosition::ConstTy),
285                        );
286                        let rhs = this.lower_const_item_rhs(attrs, rhs.as_ref(), span);
287                        (ty, rhs)
288                    },
289                );
290                self.lower_define_opaque(hir_id, &define_opaque);
291                hir::ItemKind::Const(ident, generics, ty, rhs)
292            }
293            ItemKind::Fn(box Fn {
294                sig: FnSig { decl, header, span: fn_sig_span },
295                ident,
296                generics,
297                body,
298                contract,
299                define_opaque,
300                ..
301            }) => {
302                self.with_new_scopes(*fn_sig_span, |this| {
303                    // Note: we don't need to change the return type from `T` to
304                    // `impl Future<Output = T>` here because lower_body
305                    // only cares about the input argument patterns in the function
306                    // declaration (decl), not the return types.
307                    let coroutine_kind = header.coroutine_kind;
308                    let body_id = this.lower_maybe_coroutine_body(
309                        *fn_sig_span,
310                        span,
311                        hir_id,
312                        decl,
313                        coroutine_kind,
314                        body.as_deref(),
315                        attrs,
316                        contract.as_deref(),
317                    );
318
319                    let itctx = ImplTraitContext::Universal;
320                    let (generics, decl) = this.lower_generics(generics, id, itctx, |this| {
321                        this.lower_fn_decl(decl, id, *fn_sig_span, FnDeclKind::Fn, coroutine_kind)
322                    });
323                    let sig = hir::FnSig {
324                        decl,
325                        header: this.lower_fn_header(*header, hir::Safety::Safe, attrs),
326                        span: this.lower_span(*fn_sig_span),
327                    };
328                    this.lower_define_opaque(hir_id, define_opaque);
329                    let ident = this.lower_ident(*ident);
330                    hir::ItemKind::Fn {
331                        ident,
332                        sig,
333                        generics,
334                        body: body_id,
335                        has_body: body.is_some(),
336                    }
337                })
338            }
339            ItemKind::Mod(_, ident, mod_kind) => {
340                let ident = self.lower_ident(*ident);
341                match mod_kind {
342                    ModKind::Loaded(items, _, spans) => {
343                        hir::ItemKind::Mod(ident, self.lower_mod(items, spans))
344                    }
345                    ModKind::Unloaded => panic!("`mod` items should have been loaded by now"),
346                }
347            }
348            ItemKind::ForeignMod(fm) => hir::ItemKind::ForeignMod {
349                abi: fm.abi.map_or(ExternAbi::FALLBACK, |abi| self.lower_abi(abi)),
350                items: self
351                    .arena
352                    .alloc_from_iter(fm.items.iter().map(|x| self.lower_foreign_item_ref(x))),
353            },
354            ItemKind::GlobalAsm(asm) => {
355                let asm = self.lower_inline_asm(span, asm);
356                let fake_body =
357                    self.lower_body(|this| (&[], this.expr(span, hir::ExprKind::InlineAsm(asm))));
358                hir::ItemKind::GlobalAsm { asm, fake_body }
359            }
360            ItemKind::TyAlias(box TyAlias { ident, generics, after_where_clause, ty, .. }) => {
361                // We lower
362                //
363                // type Foo = impl Trait
364                //
365                // to
366                //
367                // type Foo = Foo1
368                // opaque type Foo1: Trait
369                let ident = self.lower_ident(*ident);
370                let mut generics = generics.clone();
371                add_ty_alias_where_clause(&mut generics, after_where_clause, true);
372                let (generics, ty) = self.lower_generics(
373                    &generics,
374                    id,
375                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
376                    |this| match ty {
377                        None => {
378                            let guar = this.dcx().span_delayed_bug(
379                                span,
380                                "expected to lower type alias type, but it was missing",
381                            );
382                            this.arena.alloc(this.ty(span, hir::TyKind::Err(guar)))
383                        }
384                        Some(ty) => this.lower_ty_alloc(
385                            ty,
386                            ImplTraitContext::OpaqueTy {
387                                origin: hir::OpaqueTyOrigin::TyAlias {
388                                    parent: this.local_def_id(id),
389                                    in_assoc_ty: false,
390                                },
391                            },
392                        ),
393                    },
394                );
395                hir::ItemKind::TyAlias(ident, generics, ty)
396            }
397            ItemKind::Enum(ident, generics, enum_definition) => {
398                let ident = self.lower_ident(*ident);
399                let (generics, variants) = self.lower_generics(
400                    generics,
401                    id,
402                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
403                    |this| {
404                        this.arena.alloc_from_iter(
405                            enum_definition.variants.iter().map(|x| this.lower_variant(i, x)),
406                        )
407                    },
408                );
409                hir::ItemKind::Enum(ident, generics, hir::EnumDef { variants })
410            }
411            ItemKind::Struct(ident, generics, struct_def) => {
412                let ident = self.lower_ident(*ident);
413                let (generics, struct_def) = self.lower_generics(
414                    generics,
415                    id,
416                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
417                    |this| this.lower_variant_data(hir_id, i, struct_def),
418                );
419                hir::ItemKind::Struct(ident, generics, struct_def)
420            }
421            ItemKind::Union(ident, generics, vdata) => {
422                let ident = self.lower_ident(*ident);
423                let (generics, vdata) = self.lower_generics(
424                    generics,
425                    id,
426                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
427                    |this| this.lower_variant_data(hir_id, i, vdata),
428                );
429                hir::ItemKind::Union(ident, generics, vdata)
430            }
431            ItemKind::Impl(Impl {
432                generics: ast_generics,
433                of_trait,
434                self_ty: ty,
435                items: impl_items,
436                constness,
437            }) => {
438                // Lower the "impl header" first. This ordering is important
439                // for in-band lifetimes! Consider `'a` here:
440                //
441                //     impl Foo<'a> for u32 {
442                //         fn method(&'a self) { .. }
443                //     }
444                //
445                // Because we start by lowering the `Foo<'a> for u32`
446                // part, we will add `'a` to the list of generics on
447                // the impl. When we then encounter it later in the
448                // method, it will not be considered an in-band
449                // lifetime to be added, but rather a reference to a
450                // parent lifetime.
451                let itctx = ImplTraitContext::Universal;
452                let (generics, (of_trait, lowered_ty)) =
453                    self.lower_generics(ast_generics, id, itctx, |this| {
454                        let of_trait = of_trait
455                            .as_deref()
456                            .map(|of_trait| this.lower_trait_impl_header(of_trait));
457
458                        let lowered_ty = this.lower_ty_alloc(
459                            ty,
460                            ImplTraitContext::Disallowed(ImplTraitPosition::ImplSelf),
461                        );
462
463                        (of_trait, lowered_ty)
464                    });
465
466                let new_impl_items = self
467                    .arena
468                    .alloc_from_iter(impl_items.iter().map(|item| self.lower_impl_item_ref(item)));
469
470                let constness = self.lower_constness(*constness);
471
472                hir::ItemKind::Impl(hir::Impl {
473                    generics,
474                    of_trait,
475                    self_ty: lowered_ty,
476                    items: new_impl_items,
477                    constness,
478                })
479            }
480            ItemKind::Trait(box Trait {
481                constness,
482                is_auto,
483                safety,
484                ident,
485                generics,
486                bounds,
487                items,
488            }) => {
489                let constness = self.lower_constness(*constness);
490                let ident = self.lower_ident(*ident);
491                let (generics, (safety, items, bounds)) = self.lower_generics(
492                    generics,
493                    id,
494                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
495                    |this| {
496                        let bounds = this.lower_param_bounds(
497                            bounds,
498                            RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::SuperTrait),
499                            ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
500                        );
501                        let items = this.arena.alloc_from_iter(
502                            items.iter().map(|item| this.lower_trait_item_ref(item)),
503                        );
504                        let safety = this.lower_safety(*safety, hir::Safety::Safe);
505                        (safety, items, bounds)
506                    },
507                );
508                hir::ItemKind::Trait(constness, *is_auto, safety, ident, generics, bounds, items)
509            }
510            ItemKind::TraitAlias(box TraitAlias { constness, ident, generics, bounds }) => {
511                let constness = self.lower_constness(*constness);
512                let ident = self.lower_ident(*ident);
513                let (generics, bounds) = self.lower_generics(
514                    generics,
515                    id,
516                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
517                    |this| {
518                        this.lower_param_bounds(
519                            bounds,
520                            RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::TraitAlias),
521                            ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
522                        )
523                    },
524                );
525                hir::ItemKind::TraitAlias(constness, ident, generics, bounds)
526            }
527            ItemKind::MacroDef(ident, MacroDef { body, macro_rules, eii_extern_target: _ }) => {
528                let ident = self.lower_ident(*ident);
529                let body = Box::new(self.lower_delim_args(body));
530                let def_id = self.local_def_id(id);
531                let def_kind = self.tcx.def_kind(def_id);
532                let DefKind::Macro(macro_kinds) = def_kind else {
533                    unreachable!(
534                        "expected DefKind::Macro for macro item, found {}",
535                        def_kind.descr(def_id.to_def_id())
536                    );
537                };
538                let macro_def = self.arena.alloc(ast::MacroDef {
539                    body,
540                    macro_rules: *macro_rules,
541                    eii_extern_target: None,
542                });
543                hir::ItemKind::Macro(ident, macro_def, macro_kinds)
544            }
545            ItemKind::Delegation(box delegation) => {
546                let delegation_results = self.lower_delegation(delegation, id);
547                hir::ItemKind::Fn {
548                    sig: delegation_results.sig,
549                    ident: delegation_results.ident,
550                    generics: delegation_results.generics,
551                    body: delegation_results.body_id,
552                    has_body: true,
553                }
554            }
555            ItemKind::MacCall(..) | ItemKind::DelegationMac(..) => {
556                panic!("macros should have been expanded by now")
557            }
558        }
559    }
560
561    fn lower_path_simple_eii(&mut self, id: NodeId, path: &Path) -> Option<DefId> {
562        let res = self.resolver.get_partial_res(id)?;
563        let Some(did) = res.expect_full_res().opt_def_id() else {
564            self.dcx().span_delayed_bug(path.span, "should have errored in resolve");
565            return None;
566        };
567
568        Some(did)
569    }
570
571    #[instrument(level = "debug", skip(self))]
572    fn lower_use_tree(
573        &mut self,
574        tree: &UseTree,
575        prefix: &Path,
576        id: NodeId,
577        vis_span: Span,
578        attrs: &'hir [hir::Attribute],
579    ) -> hir::ItemKind<'hir> {
580        let path = &tree.prefix;
581        let segments = prefix.segments.iter().chain(path.segments.iter()).cloned().collect();
582
583        match tree.kind {
584            UseTreeKind::Simple(rename) => {
585                let mut ident = tree.ident();
586
587                // First, apply the prefix to the path.
588                let mut path = Path { segments, span: path.span, tokens: None };
589
590                // Correctly resolve `self` imports.
591                if path.segments.len() > 1
592                    && path.segments.last().unwrap().ident.name == kw::SelfLower
593                {
594                    let _ = path.segments.pop();
595                    if rename.is_none() {
596                        ident = path.segments.last().unwrap().ident;
597                    }
598                }
599
600                let res = self.lower_import_res(id, path.span);
601                let path = self.lower_use_path(res, &path, ParamMode::Explicit);
602                let ident = self.lower_ident(ident);
603                hir::ItemKind::Use(path, hir::UseKind::Single(ident))
604            }
605            UseTreeKind::Glob => {
606                let res = self.expect_full_res(id);
607                let res = self.lower_res(res);
608                // Put the result in the appropriate namespace.
609                let res = match res {
610                    Res::Def(DefKind::Mod | DefKind::Trait, _) => {
611                        PerNS { type_ns: Some(res), value_ns: None, macro_ns: None }
612                    }
613                    Res::Def(DefKind::Enum, _) => {
614                        PerNS { type_ns: None, value_ns: Some(res), macro_ns: None }
615                    }
616                    Res::Err => {
617                        // Propagate the error to all namespaces, just to be sure.
618                        let err = Some(Res::Err);
619                        PerNS { type_ns: err, value_ns: err, macro_ns: err }
620                    }
621                    _ => span_bug!(path.span, "bad glob res {:?}", res),
622                };
623                let path = Path { segments, span: path.span, tokens: None };
624                let path = self.lower_use_path(res, &path, ParamMode::Explicit);
625                hir::ItemKind::Use(path, hir::UseKind::Glob)
626            }
627            UseTreeKind::Nested { items: ref trees, .. } => {
628                // Nested imports are desugared into simple imports.
629                // So, if we start with
630                //
631                // ```
632                // pub(x) use foo::{a, b};
633                // ```
634                //
635                // we will create three items:
636                //
637                // ```
638                // pub(x) use foo::a;
639                // pub(x) use foo::b;
640                // pub(x) use foo::{}; // <-- this is called the `ListStem`
641                // ```
642                //
643                // The first two are produced by recursively invoking
644                // `lower_use_tree` (and indeed there may be things
645                // like `use foo::{a::{b, c}}` and so forth). They
646                // wind up being directly added to
647                // `self.items`. However, the structure of this
648                // function also requires us to return one item, and
649                // for that we return the `{}` import (called the
650                // `ListStem`).
651
652                let span = prefix.span.to(path.span);
653                let prefix = Path { segments, span, tokens: None };
654
655                // Add all the nested `PathListItem`s to the HIR.
656                for &(ref use_tree, id) in trees {
657                    let owner_id = self.owner_id(id);
658
659                    // Each `use` import is an item and thus are owners of the
660                    // names in the path. Up to this point the nested import is
661                    // the current owner, since we want each desugared import to
662                    // own its own names, we have to adjust the owner before
663                    // lowering the rest of the import.
664                    self.with_hir_id_owner(id, |this| {
665                        // `prefix` is lowered multiple times, but in different HIR owners.
666                        // So each segment gets renewed `HirId` with the same
667                        // `ItemLocalId` and the new owner. (See `lower_node_id`)
668                        let kind = this.lower_use_tree(use_tree, &prefix, id, vis_span, attrs);
669                        if !attrs.is_empty() {
670                            this.attrs.insert(hir::ItemLocalId::ZERO, attrs);
671                        }
672
673                        let item = hir::Item {
674                            owner_id,
675                            kind,
676                            vis_span,
677                            span: this.lower_span(use_tree.span),
678                            has_delayed_lints: !this.delayed_lints.is_empty(),
679                            eii: find_attr!(
680                                attrs,
681                                AttributeKind::EiiImpls(..) | AttributeKind::EiiExternTarget(..)
682                            ),
683                        };
684                        hir::OwnerNode::Item(this.arena.alloc(item))
685                    });
686                }
687
688                // Condition should match `build_reduced_graph_for_use_tree`.
689                let path = if trees.is_empty()
690                    && !(prefix.segments.is_empty()
691                        || prefix.segments.len() == 1
692                            && prefix.segments[0].ident.name == kw::PathRoot)
693                {
694                    // For empty lists we need to lower the prefix so it is checked for things
695                    // like stability later.
696                    let res = self.lower_import_res(id, span);
697                    self.lower_use_path(res, &prefix, ParamMode::Explicit)
698                } else {
699                    // For non-empty lists we can just drop all the data, the prefix is already
700                    // present in HIR as a part of nested imports.
701                    let span = self.lower_span(span);
702                    self.arena.alloc(hir::UsePath { res: PerNS::default(), segments: &[], span })
703                };
704                hir::ItemKind::Use(path, hir::UseKind::ListStem)
705            }
706        }
707    }
708
709    fn lower_assoc_item(&mut self, item: &AssocItem, ctxt: AssocCtxt) -> hir::OwnerNode<'hir> {
710        // Evaluate with the lifetimes in `params` in-scope.
711        // This is used to track which lifetimes have already been defined,
712        // and which need to be replicated when lowering an async fn.
713        match ctxt {
714            AssocCtxt::Trait => hir::OwnerNode::TraitItem(self.lower_trait_item(item)),
715            AssocCtxt::Impl { of_trait } => {
716                hir::OwnerNode::ImplItem(self.lower_impl_item(item, of_trait))
717            }
718        }
719    }
720
721    fn lower_foreign_item(&mut self, i: &ForeignItem) -> &'hir hir::ForeignItem<'hir> {
722        let hir_id = hir::HirId::make_owner(self.current_hir_id_owner.def_id);
723        let owner_id = hir_id.expect_owner();
724        let attrs =
725            self.lower_attrs(hir_id, &i.attrs, i.span, Target::from_foreign_item_kind(&i.kind));
726        let (ident, kind) = match &i.kind {
727            ForeignItemKind::Fn(box Fn { sig, ident, generics, define_opaque, .. }) => {
728                let fdec = &sig.decl;
729                let itctx = ImplTraitContext::Universal;
730                let (generics, (decl, fn_args)) =
731                    self.lower_generics(generics, i.id, itctx, |this| {
732                        (
733                            // Disallow `impl Trait` in foreign items.
734                            this.lower_fn_decl(fdec, i.id, sig.span, FnDeclKind::ExternFn, None),
735                            this.lower_fn_params_to_idents(fdec),
736                        )
737                    });
738
739                // Unmarked safety in unsafe block defaults to unsafe.
740                let header = self.lower_fn_header(sig.header, hir::Safety::Unsafe, attrs);
741
742                if define_opaque.is_some() {
743                    self.dcx().span_err(i.span, "foreign functions cannot define opaque types");
744                }
745
746                (
747                    ident,
748                    hir::ForeignItemKind::Fn(
749                        hir::FnSig { header, decl, span: self.lower_span(sig.span) },
750                        fn_args,
751                        generics,
752                    ),
753                )
754            }
755            ForeignItemKind::Static(box StaticItem {
756                ident,
757                ty,
758                mutability,
759                expr: _,
760                safety,
761                define_opaque,
762            }) => {
763                let ty = self
764                    .lower_ty_alloc(ty, ImplTraitContext::Disallowed(ImplTraitPosition::StaticTy));
765                let safety = self.lower_safety(*safety, hir::Safety::Unsafe);
766                if define_opaque.is_some() {
767                    self.dcx().span_err(i.span, "foreign statics cannot define opaque types");
768                }
769                (ident, hir::ForeignItemKind::Static(ty, *mutability, safety))
770            }
771            ForeignItemKind::TyAlias(box TyAlias { ident, .. }) => {
772                (ident, hir::ForeignItemKind::Type)
773            }
774            ForeignItemKind::MacCall(_) => panic!("macro shouldn't exist here"),
775        };
776
777        let item = hir::ForeignItem {
778            owner_id,
779            ident: self.lower_ident(*ident),
780            kind,
781            vis_span: self.lower_span(i.vis.span),
782            span: self.lower_span(i.span),
783            has_delayed_lints: !self.delayed_lints.is_empty(),
784        };
785        self.arena.alloc(item)
786    }
787
788    fn lower_foreign_item_ref(&mut self, i: &ForeignItem) -> hir::ForeignItemId {
789        hir::ForeignItemId { owner_id: self.owner_id(i.id) }
790    }
791
792    fn lower_variant(&mut self, item_kind: &ItemKind, v: &Variant) -> hir::Variant<'hir> {
793        let hir_id = self.lower_node_id(v.id);
794        self.lower_attrs(hir_id, &v.attrs, v.span, Target::Variant);
795        hir::Variant {
796            hir_id,
797            def_id: self.local_def_id(v.id),
798            data: self.lower_variant_data(hir_id, item_kind, &v.data),
799            disr_expr: v.disr_expr.as_ref().map(|e| self.lower_anon_const_to_anon_const(e)),
800            ident: self.lower_ident(v.ident),
801            span: self.lower_span(v.span),
802        }
803    }
804
805    fn lower_variant_data(
806        &mut self,
807        parent_id: hir::HirId,
808        item_kind: &ItemKind,
809        vdata: &VariantData,
810    ) -> hir::VariantData<'hir> {
811        match vdata {
812            VariantData::Struct { fields, recovered } => {
813                let fields = self
814                    .arena
815                    .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_field_def(f)));
816
817                if let ItemKind::Union(..) = item_kind {
818                    for field in &fields[..] {
819                        if let Some(default) = field.default {
820                            // Unions cannot derive `Default`, and it's not clear how to use default
821                            // field values of unions if that was supported. Therefore, blanket reject
822                            // trying to use field values with unions.
823                            if self.tcx.features().default_field_values() {
824                                self.dcx().emit_err(UnionWithDefault { span: default.span });
825                            } else {
826                                let _ = self.dcx().span_delayed_bug(
827                                default.span,
828                                "expected union default field values feature gate error but none \
829                                was produced",
830                            );
831                            }
832                        }
833                    }
834                }
835
836                hir::VariantData::Struct { fields, recovered: *recovered }
837            }
838            VariantData::Tuple(fields, id) => {
839                let ctor_id = self.lower_node_id(*id);
840                self.alias_attrs(ctor_id, parent_id);
841                let fields = self
842                    .arena
843                    .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_field_def(f)));
844                for field in &fields[..] {
845                    if let Some(default) = field.default {
846                        // Default values in tuple struct and tuple variants are not allowed by the
847                        // RFC due to concerns about the syntax, both in the item definition and the
848                        // expression. We could in the future allow `struct S(i32 = 0);` and force
849                        // users to construct the value with `let _ = S { .. };`.
850                        if self.tcx.features().default_field_values() {
851                            self.dcx().emit_err(TupleStructWithDefault { span: default.span });
852                        } else {
853                            let _ = self.dcx().span_delayed_bug(
854                                default.span,
855                                "expected `default values on `struct` fields aren't supported` \
856                                 feature-gate error but none was produced",
857                            );
858                        }
859                    }
860                }
861                hir::VariantData::Tuple(fields, ctor_id, self.local_def_id(*id))
862            }
863            VariantData::Unit(id) => {
864                let ctor_id = self.lower_node_id(*id);
865                self.alias_attrs(ctor_id, parent_id);
866                hir::VariantData::Unit(ctor_id, self.local_def_id(*id))
867            }
868        }
869    }
870
871    pub(super) fn lower_field_def(
872        &mut self,
873        (index, f): (usize, &FieldDef),
874    ) -> hir::FieldDef<'hir> {
875        let ty =
876            self.lower_ty_alloc(&f.ty, ImplTraitContext::Disallowed(ImplTraitPosition::FieldTy));
877        let hir_id = self.lower_node_id(f.id);
878        self.lower_attrs(hir_id, &f.attrs, f.span, Target::Field);
879        hir::FieldDef {
880            span: self.lower_span(f.span),
881            hir_id,
882            def_id: self.local_def_id(f.id),
883            ident: match f.ident {
884                Some(ident) => self.lower_ident(ident),
885                // FIXME(jseyfried): positional field hygiene.
886                None => Ident::new(sym::integer(index), self.lower_span(f.span)),
887            },
888            vis_span: self.lower_span(f.vis.span),
889            default: f.default.as_ref().map(|v| self.lower_anon_const_to_anon_const(v)),
890            ty,
891            safety: self.lower_safety(f.safety, hir::Safety::Safe),
892        }
893    }
894
895    fn lower_trait_item(&mut self, i: &AssocItem) -> &'hir hir::TraitItem<'hir> {
896        let hir_id = hir::HirId::make_owner(self.current_hir_id_owner.def_id);
897        let attrs = self.lower_attrs(
898            hir_id,
899            &i.attrs,
900            i.span,
901            Target::from_assoc_item_kind(&i.kind, AssocCtxt::Trait),
902        );
903        let trait_item_def_id = hir_id.expect_owner();
904
905        let (ident, generics, kind, has_default) = match &i.kind {
906            AssocItemKind::Const(box ConstItem {
907                ident, generics, ty, rhs, define_opaque, ..
908            }) => {
909                let (generics, kind) = self.lower_generics(
910                    generics,
911                    i.id,
912                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
913                    |this| {
914                        let ty = this.lower_ty_alloc(
915                            ty,
916                            ImplTraitContext::Disallowed(ImplTraitPosition::ConstTy),
917                        );
918                        let rhs = rhs
919                            .as_ref()
920                            .map(|rhs| this.lower_const_item_rhs(attrs, Some(rhs), i.span));
921                        hir::TraitItemKind::Const(ty, rhs)
922                    },
923                );
924
925                if define_opaque.is_some() {
926                    if rhs.is_some() {
927                        self.lower_define_opaque(hir_id, &define_opaque);
928                    } else {
929                        self.dcx().span_err(
930                            i.span,
931                            "only trait consts with default bodies can define opaque types",
932                        );
933                    }
934                }
935
936                (*ident, generics, kind, rhs.is_some())
937            }
938            AssocItemKind::Fn(box Fn {
939                sig, ident, generics, body: None, define_opaque, ..
940            }) => {
941                // FIXME(contracts): Deny contract here since it won't apply to
942                // any impl method or callees.
943                let idents = self.lower_fn_params_to_idents(&sig.decl);
944                let (generics, sig) = self.lower_method_sig(
945                    generics,
946                    sig,
947                    i.id,
948                    FnDeclKind::Trait,
949                    sig.header.coroutine_kind,
950                    attrs,
951                );
952                if define_opaque.is_some() {
953                    self.dcx().span_err(
954                        i.span,
955                        "only trait methods with default bodies can define opaque types",
956                    );
957                }
958                (
959                    *ident,
960                    generics,
961                    hir::TraitItemKind::Fn(sig, hir::TraitFn::Required(idents)),
962                    false,
963                )
964            }
965            AssocItemKind::Fn(box Fn {
966                sig,
967                ident,
968                generics,
969                body: Some(body),
970                contract,
971                define_opaque,
972                ..
973            }) => {
974                let body_id = self.lower_maybe_coroutine_body(
975                    sig.span,
976                    i.span,
977                    hir_id,
978                    &sig.decl,
979                    sig.header.coroutine_kind,
980                    Some(body),
981                    attrs,
982                    contract.as_deref(),
983                );
984                let (generics, sig) = self.lower_method_sig(
985                    generics,
986                    sig,
987                    i.id,
988                    FnDeclKind::Trait,
989                    sig.header.coroutine_kind,
990                    attrs,
991                );
992                self.lower_define_opaque(hir_id, &define_opaque);
993                (
994                    *ident,
995                    generics,
996                    hir::TraitItemKind::Fn(sig, hir::TraitFn::Provided(body_id)),
997                    true,
998                )
999            }
1000            AssocItemKind::Type(box TyAlias {
1001                ident,
1002                generics,
1003                after_where_clause,
1004                bounds,
1005                ty,
1006                ..
1007            }) => {
1008                let mut generics = generics.clone();
1009                add_ty_alias_where_clause(&mut generics, after_where_clause, false);
1010                let (generics, kind) = self.lower_generics(
1011                    &generics,
1012                    i.id,
1013                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
1014                    |this| {
1015                        let ty = ty.as_ref().map(|x| {
1016                            this.lower_ty_alloc(
1017                                x,
1018                                ImplTraitContext::Disallowed(ImplTraitPosition::AssocTy),
1019                            )
1020                        });
1021                        hir::TraitItemKind::Type(
1022                            this.lower_param_bounds(
1023                                bounds,
1024                                RelaxedBoundPolicy::Allowed,
1025                                ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
1026                            ),
1027                            ty,
1028                        )
1029                    },
1030                );
1031                (*ident, generics, kind, ty.is_some())
1032            }
1033            AssocItemKind::Delegation(box delegation) => {
1034                let delegation_results = self.lower_delegation(delegation, i.id);
1035                let item_kind = hir::TraitItemKind::Fn(
1036                    delegation_results.sig,
1037                    hir::TraitFn::Provided(delegation_results.body_id),
1038                );
1039                (delegation.ident, delegation_results.generics, item_kind, true)
1040            }
1041            AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
1042                panic!("macros should have been expanded by now")
1043            }
1044        };
1045
1046        let item = hir::TraitItem {
1047            owner_id: trait_item_def_id,
1048            ident: self.lower_ident(ident),
1049            generics,
1050            kind,
1051            span: self.lower_span(i.span),
1052            defaultness: hir::Defaultness::Default { has_value: has_default },
1053            has_delayed_lints: !self.delayed_lints.is_empty(),
1054        };
1055        self.arena.alloc(item)
1056    }
1057
1058    fn lower_trait_item_ref(&mut self, i: &AssocItem) -> hir::TraitItemId {
1059        hir::TraitItemId { owner_id: self.owner_id(i.id) }
1060    }
1061
1062    /// Construct `ExprKind::Err` for the given `span`.
1063    pub(crate) fn expr_err(&mut self, span: Span, guar: ErrorGuaranteed) -> hir::Expr<'hir> {
1064        self.expr(span, hir::ExprKind::Err(guar))
1065    }
1066
1067    fn lower_trait_impl_header(
1068        &mut self,
1069        trait_impl_header: &TraitImplHeader,
1070    ) -> &'hir hir::TraitImplHeader<'hir> {
1071        let TraitImplHeader { safety, polarity, defaultness, ref trait_ref } = *trait_impl_header;
1072        let safety = self.lower_safety(safety, hir::Safety::Safe);
1073        let polarity = match polarity {
1074            ImplPolarity::Positive => ImplPolarity::Positive,
1075            ImplPolarity::Negative(s) => ImplPolarity::Negative(self.lower_span(s)),
1076        };
1077        // `defaultness.has_value()` is never called for an `impl`, always `true` in order
1078        // to not cause an assertion failure inside the `lower_defaultness` function.
1079        let has_val = true;
1080        let (defaultness, defaultness_span) = self.lower_defaultness(defaultness, has_val);
1081        let modifiers = TraitBoundModifiers {
1082            constness: BoundConstness::Never,
1083            asyncness: BoundAsyncness::Normal,
1084            // we don't use this in bound lowering
1085            polarity: BoundPolarity::Positive,
1086        };
1087        let trait_ref = self.lower_trait_ref(
1088            modifiers,
1089            trait_ref,
1090            ImplTraitContext::Disallowed(ImplTraitPosition::Trait),
1091        );
1092
1093        self.arena.alloc(hir::TraitImplHeader {
1094            safety,
1095            polarity,
1096            defaultness,
1097            defaultness_span,
1098            trait_ref,
1099        })
1100    }
1101
1102    fn lower_impl_item(
1103        &mut self,
1104        i: &AssocItem,
1105        is_in_trait_impl: bool,
1106    ) -> &'hir hir::ImplItem<'hir> {
1107        // Since `default impl` is not yet implemented, this is always true in impls.
1108        let has_value = true;
1109        let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value);
1110        let hir_id = hir::HirId::make_owner(self.current_hir_id_owner.def_id);
1111        let attrs = self.lower_attrs(
1112            hir_id,
1113            &i.attrs,
1114            i.span,
1115            Target::from_assoc_item_kind(&i.kind, AssocCtxt::Impl { of_trait: is_in_trait_impl }),
1116        );
1117
1118        let (ident, (generics, kind)) = match &i.kind {
1119            AssocItemKind::Const(box ConstItem {
1120                ident, generics, ty, rhs, define_opaque, ..
1121            }) => (
1122                *ident,
1123                self.lower_generics(
1124                    generics,
1125                    i.id,
1126                    ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
1127                    |this| {
1128                        let ty = this.lower_ty_alloc(
1129                            ty,
1130                            ImplTraitContext::Disallowed(ImplTraitPosition::ConstTy),
1131                        );
1132                        this.lower_define_opaque(hir_id, &define_opaque);
1133                        let rhs = this.lower_const_item_rhs(attrs, rhs.as_ref(), i.span);
1134                        hir::ImplItemKind::Const(ty, rhs)
1135                    },
1136                ),
1137            ),
1138            AssocItemKind::Fn(box Fn {
1139                sig,
1140                ident,
1141                generics,
1142                body,
1143                contract,
1144                define_opaque,
1145                ..
1146            }) => {
1147                let body_id = self.lower_maybe_coroutine_body(
1148                    sig.span,
1149                    i.span,
1150                    hir_id,
1151                    &sig.decl,
1152                    sig.header.coroutine_kind,
1153                    body.as_deref(),
1154                    attrs,
1155                    contract.as_deref(),
1156                );
1157                let (generics, sig) = self.lower_method_sig(
1158                    generics,
1159                    sig,
1160                    i.id,
1161                    if is_in_trait_impl { FnDeclKind::Impl } else { FnDeclKind::Inherent },
1162                    sig.header.coroutine_kind,
1163                    attrs,
1164                );
1165                self.lower_define_opaque(hir_id, &define_opaque);
1166
1167                (*ident, (generics, hir::ImplItemKind::Fn(sig, body_id)))
1168            }
1169            AssocItemKind::Type(box TyAlias {
1170                ident, generics, after_where_clause, ty, ..
1171            }) => {
1172                let mut generics = generics.clone();
1173                add_ty_alias_where_clause(&mut generics, after_where_clause, false);
1174                (
1175                    *ident,
1176                    self.lower_generics(
1177                        &generics,
1178                        i.id,
1179                        ImplTraitContext::Disallowed(ImplTraitPosition::Generic),
1180                        |this| match ty {
1181                            None => {
1182                                let guar = this.dcx().span_delayed_bug(
1183                                    i.span,
1184                                    "expected to lower associated type, but it was missing",
1185                                );
1186                                let ty = this.arena.alloc(this.ty(i.span, hir::TyKind::Err(guar)));
1187                                hir::ImplItemKind::Type(ty)
1188                            }
1189                            Some(ty) => {
1190                                let ty = this.lower_ty_alloc(
1191                                    ty,
1192                                    ImplTraitContext::OpaqueTy {
1193                                        origin: hir::OpaqueTyOrigin::TyAlias {
1194                                            parent: this.local_def_id(i.id),
1195                                            in_assoc_ty: true,
1196                                        },
1197                                    },
1198                                );
1199                                hir::ImplItemKind::Type(ty)
1200                            }
1201                        },
1202                    ),
1203                )
1204            }
1205            AssocItemKind::Delegation(box delegation) => {
1206                let delegation_results = self.lower_delegation(delegation, i.id);
1207                (
1208                    delegation.ident,
1209                    (
1210                        delegation_results.generics,
1211                        hir::ImplItemKind::Fn(delegation_results.sig, delegation_results.body_id),
1212                    ),
1213                )
1214            }
1215            AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
1216                panic!("macros should have been expanded by now")
1217            }
1218        };
1219
1220        let span = self.lower_span(i.span);
1221        let item = hir::ImplItem {
1222            owner_id: hir_id.expect_owner(),
1223            ident: self.lower_ident(ident),
1224            generics,
1225            impl_kind: if is_in_trait_impl {
1226                ImplItemImplKind::Trait {
1227                    defaultness,
1228                    trait_item_def_id: self
1229                        .resolver
1230                        .get_partial_res(i.id)
1231                        .and_then(|r| r.expect_full_res().opt_def_id())
1232                        .ok_or_else(|| {
1233                            self.dcx().span_delayed_bug(
1234                                span,
1235                                "could not resolve trait item being implemented",
1236                            )
1237                        }),
1238                }
1239            } else {
1240                ImplItemImplKind::Inherent { vis_span: self.lower_span(i.vis.span) }
1241            },
1242            kind,
1243            span,
1244            has_delayed_lints: !self.delayed_lints.is_empty(),
1245        };
1246        self.arena.alloc(item)
1247    }
1248
1249    fn lower_impl_item_ref(&mut self, i: &AssocItem) -> hir::ImplItemId {
1250        hir::ImplItemId { owner_id: self.owner_id(i.id) }
1251    }
1252
1253    fn lower_defaultness(
1254        &self,
1255        d: Defaultness,
1256        has_value: bool,
1257    ) -> (hir::Defaultness, Option<Span>) {
1258        match d {
1259            Defaultness::Default(sp) => {
1260                (hir::Defaultness::Default { has_value }, Some(self.lower_span(sp)))
1261            }
1262            Defaultness::Final => {
1263                assert!(has_value);
1264                (hir::Defaultness::Final, None)
1265            }
1266        }
1267    }
1268
1269    fn record_body(
1270        &mut self,
1271        params: &'hir [hir::Param<'hir>],
1272        value: hir::Expr<'hir>,
1273    ) -> hir::BodyId {
1274        let body = hir::Body { params, value: self.arena.alloc(value) };
1275        let id = body.id();
1276        assert_eq!(id.hir_id.owner, self.current_hir_id_owner);
1277        self.bodies.push((id.hir_id.local_id, self.arena.alloc(body)));
1278        id
1279    }
1280
1281    pub(super) fn lower_body(
1282        &mut self,
1283        f: impl FnOnce(&mut Self) -> (&'hir [hir::Param<'hir>], hir::Expr<'hir>),
1284    ) -> hir::BodyId {
1285        let prev_coroutine_kind = self.coroutine_kind.take();
1286        let task_context = self.task_context.take();
1287        let (parameters, result) = f(self);
1288        let body_id = self.record_body(parameters, result);
1289        self.task_context = task_context;
1290        self.coroutine_kind = prev_coroutine_kind;
1291        body_id
1292    }
1293
1294    fn lower_param(&mut self, param: &Param) -> hir::Param<'hir> {
1295        let hir_id = self.lower_node_id(param.id);
1296        self.lower_attrs(hir_id, &param.attrs, param.span, Target::Param);
1297        hir::Param {
1298            hir_id,
1299            pat: self.lower_pat(&param.pat),
1300            ty_span: self.lower_span(param.ty.span),
1301            span: self.lower_span(param.span),
1302        }
1303    }
1304
1305    pub(super) fn lower_fn_body(
1306        &mut self,
1307        decl: &FnDecl,
1308        contract: Option<&FnContract>,
1309        body: impl FnOnce(&mut Self) -> hir::Expr<'hir>,
1310    ) -> hir::BodyId {
1311        self.lower_body(|this| {
1312            let params =
1313                this.arena.alloc_from_iter(decl.inputs.iter().map(|x| this.lower_param(x)));
1314
1315            // Optionally lower the fn contract
1316            if let Some(contract) = contract {
1317                (params, this.lower_contract(body, contract))
1318            } else {
1319                (params, body(this))
1320            }
1321        })
1322    }
1323
1324    fn lower_fn_body_block(
1325        &mut self,
1326        decl: &FnDecl,
1327        body: &Block,
1328        contract: Option<&FnContract>,
1329    ) -> hir::BodyId {
1330        self.lower_fn_body(decl, contract, |this| this.lower_block_expr(body))
1331    }
1332
1333    pub(super) fn lower_const_body(&mut self, span: Span, expr: Option<&Expr>) -> hir::BodyId {
1334        self.lower_body(|this| {
1335            (
1336                &[],
1337                match expr {
1338                    Some(expr) => this.lower_expr_mut(expr),
1339                    None => this.expr_err(span, this.dcx().span_delayed_bug(span, "no block")),
1340                },
1341            )
1342        })
1343    }
1344
1345    /// Takes what may be the body of an `async fn` or a `gen fn` and wraps it in an `async {}` or
1346    /// `gen {}` block as appropriate.
1347    fn lower_maybe_coroutine_body(
1348        &mut self,
1349        fn_decl_span: Span,
1350        span: Span,
1351        fn_id: hir::HirId,
1352        decl: &FnDecl,
1353        coroutine_kind: Option<CoroutineKind>,
1354        body: Option<&Block>,
1355        attrs: &'hir [hir::Attribute],
1356        contract: Option<&FnContract>,
1357    ) -> hir::BodyId {
1358        let Some(body) = body else {
1359            // Functions without a body are an error, except if this is an intrinsic. For those we
1360            // create a fake body so that the entire rest of the compiler doesn't have to deal with
1361            // this as a special case.
1362            return self.lower_fn_body(decl, contract, |this| {
1363                if attrs.iter().any(|a| a.has_name(sym::rustc_intrinsic))
1364                    || this.tcx.is_sdylib_interface_build()
1365                {
1366                    let span = this.lower_span(span);
1367                    let empty_block = hir::Block {
1368                        hir_id: this.next_id(),
1369                        stmts: &[],
1370                        expr: None,
1371                        rules: hir::BlockCheckMode::DefaultBlock,
1372                        span,
1373                        targeted_by_break: false,
1374                    };
1375                    let loop_ = hir::ExprKind::Loop(
1376                        this.arena.alloc(empty_block),
1377                        None,
1378                        hir::LoopSource::Loop,
1379                        span,
1380                    );
1381                    hir::Expr { hir_id: this.next_id(), kind: loop_, span }
1382                } else {
1383                    this.expr_err(span, this.dcx().has_errors().unwrap())
1384                }
1385            });
1386        };
1387        let Some(coroutine_kind) = coroutine_kind else {
1388            // Typical case: not a coroutine.
1389            return self.lower_fn_body_block(decl, body, contract);
1390        };
1391        // FIXME(contracts): Support contracts on async fn.
1392        self.lower_body(|this| {
1393            let (parameters, expr) = this.lower_coroutine_body_with_moved_arguments(
1394                decl,
1395                |this| this.lower_block_expr(body),
1396                fn_decl_span,
1397                body.span,
1398                coroutine_kind,
1399                hir::CoroutineSource::Fn,
1400            );
1401
1402            // FIXME(async_fn_track_caller): Can this be moved above?
1403            let hir_id = expr.hir_id;
1404            this.maybe_forward_track_caller(body.span, fn_id, hir_id);
1405
1406            (parameters, expr)
1407        })
1408    }
1409
1410    /// Lowers a desugared coroutine body after moving all of the arguments
1411    /// into the body. This is to make sure that the future actually owns the
1412    /// arguments that are passed to the function, and to ensure things like
1413    /// drop order are stable.
1414    pub(crate) fn lower_coroutine_body_with_moved_arguments(
1415        &mut self,
1416        decl: &FnDecl,
1417        lower_body: impl FnOnce(&mut LoweringContext<'_, 'hir>) -> hir::Expr<'hir>,
1418        fn_decl_span: Span,
1419        body_span: Span,
1420        coroutine_kind: CoroutineKind,
1421        coroutine_source: hir::CoroutineSource,
1422    ) -> (&'hir [hir::Param<'hir>], hir::Expr<'hir>) {
1423        let mut parameters: Vec<hir::Param<'_>> = Vec::new();
1424        let mut statements: Vec<hir::Stmt<'_>> = Vec::new();
1425
1426        // Async function parameters are lowered into the closure body so that they are
1427        // captured and so that the drop order matches the equivalent non-async functions.
1428        //
1429        // from:
1430        //
1431        //     async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) {
1432        //         <body>
1433        //     }
1434        //
1435        // into:
1436        //
1437        //     fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) {
1438        //       async move {
1439        //         let __arg2 = __arg2;
1440        //         let <pattern> = __arg2;
1441        //         let __arg1 = __arg1;
1442        //         let <pattern> = __arg1;
1443        //         let __arg0 = __arg0;
1444        //         let <pattern> = __arg0;
1445        //         drop-temps { <body> } // see comments later in fn for details
1446        //       }
1447        //     }
1448        //
1449        // If `<pattern>` is a simple ident, then it is lowered to a single
1450        // `let <pattern> = <pattern>;` statement as an optimization.
1451        //
1452        // Note that the body is embedded in `drop-temps`; an
1453        // equivalent desugaring would be `return { <body>
1454        // };`. The key point is that we wish to drop all the
1455        // let-bound variables and temporaries created in the body
1456        // (and its tail expression!) before we drop the
1457        // parameters (c.f. rust-lang/rust#64512).
1458        for (index, parameter) in decl.inputs.iter().enumerate() {
1459            let parameter = self.lower_param(parameter);
1460            let span = parameter.pat.span;
1461
1462            // Check if this is a binding pattern, if so, we can optimize and avoid adding a
1463            // `let <pat> = __argN;` statement. In this case, we do not rename the parameter.
1464            let (ident, is_simple_parameter) = match parameter.pat.kind {
1465                hir::PatKind::Binding(hir::BindingMode(ByRef::No, _), _, ident, _) => (ident, true),
1466                // For `ref mut` or wildcard arguments, we can't reuse the binding, but
1467                // we can keep the same name for the parameter.
1468                // This lets rustdoc render it correctly in documentation.
1469                hir::PatKind::Binding(_, _, ident, _) => (ident, false),
1470                hir::PatKind::Wild => (Ident::with_dummy_span(rustc_span::kw::Underscore), false),
1471                _ => {
1472                    // Replace the ident for bindings that aren't simple.
1473                    let name = format!("__arg{index}");
1474                    let ident = Ident::from_str(&name);
1475
1476                    (ident, false)
1477                }
1478            };
1479
1480            let desugared_span = self.mark_span_with_reason(DesugaringKind::Async, span, None);
1481
1482            // Construct a parameter representing `__argN: <ty>` to replace the parameter of the
1483            // async function.
1484            //
1485            // If this is the simple case, this parameter will end up being the same as the
1486            // original parameter, but with a different pattern id.
1487            let stmt_attrs = self.attrs.get(&parameter.hir_id.local_id).copied();
1488            let (new_parameter_pat, new_parameter_id) = self.pat_ident(desugared_span, ident);
1489            let new_parameter = hir::Param {
1490                hir_id: parameter.hir_id,
1491                pat: new_parameter_pat,
1492                ty_span: self.lower_span(parameter.ty_span),
1493                span: self.lower_span(parameter.span),
1494            };
1495
1496            if is_simple_parameter {
1497                // If this is the simple case, then we only insert one statement that is
1498                // `let <pat> = <pat>;`. We re-use the original argument's pattern so that
1499                // `HirId`s are densely assigned.
1500                let expr = self.expr_ident(desugared_span, ident, new_parameter_id);
1501                let stmt = self.stmt_let_pat(
1502                    stmt_attrs,
1503                    desugared_span,
1504                    Some(expr),
1505                    parameter.pat,
1506                    hir::LocalSource::AsyncFn,
1507                );
1508                statements.push(stmt);
1509            } else {
1510                // If this is not the simple case, then we construct two statements:
1511                //
1512                // ```
1513                // let __argN = __argN;
1514                // let <pat> = __argN;
1515                // ```
1516                //
1517                // The first statement moves the parameter into the closure and thus ensures
1518                // that the drop order is correct.
1519                //
1520                // The second statement creates the bindings that the user wrote.
1521
1522                // Construct the `let mut __argN = __argN;` statement. It must be a mut binding
1523                // because the user may have specified a `ref mut` binding in the next
1524                // statement.
1525                let (move_pat, move_id) =
1526                    self.pat_ident_binding_mode(desugared_span, ident, hir::BindingMode::MUT);
1527                let move_expr = self.expr_ident(desugared_span, ident, new_parameter_id);
1528                let move_stmt = self.stmt_let_pat(
1529                    None,
1530                    desugared_span,
1531                    Some(move_expr),
1532                    move_pat,
1533                    hir::LocalSource::AsyncFn,
1534                );
1535
1536                // Construct the `let <pat> = __argN;` statement. We re-use the original
1537                // parameter's pattern so that `HirId`s are densely assigned.
1538                let pattern_expr = self.expr_ident(desugared_span, ident, move_id);
1539                let pattern_stmt = self.stmt_let_pat(
1540                    stmt_attrs,
1541                    desugared_span,
1542                    Some(pattern_expr),
1543                    parameter.pat,
1544                    hir::LocalSource::AsyncFn,
1545                );
1546
1547                statements.push(move_stmt);
1548                statements.push(pattern_stmt);
1549            };
1550
1551            parameters.push(new_parameter);
1552        }
1553
1554        let mkbody = |this: &mut LoweringContext<'_, 'hir>| {
1555            // Create a block from the user's function body:
1556            let user_body = lower_body(this);
1557
1558            // Transform into `drop-temps { <user-body> }`, an expression:
1559            let desugared_span =
1560                this.mark_span_with_reason(DesugaringKind::Async, user_body.span, None);
1561            let user_body = this.expr_drop_temps(desugared_span, this.arena.alloc(user_body));
1562
1563            // As noted above, create the final block like
1564            //
1565            // ```
1566            // {
1567            //   let $param_pattern = $raw_param;
1568            //   ...
1569            //   drop-temps { <user-body> }
1570            // }
1571            // ```
1572            let body = this.block_all(
1573                desugared_span,
1574                this.arena.alloc_from_iter(statements),
1575                Some(user_body),
1576            );
1577
1578            this.expr_block(body)
1579        };
1580        let desugaring_kind = match coroutine_kind {
1581            CoroutineKind::Async { .. } => hir::CoroutineDesugaring::Async,
1582            CoroutineKind::Gen { .. } => hir::CoroutineDesugaring::Gen,
1583            CoroutineKind::AsyncGen { .. } => hir::CoroutineDesugaring::AsyncGen,
1584        };
1585        let closure_id = coroutine_kind.closure_id();
1586
1587        let coroutine_expr = self.make_desugared_coroutine_expr(
1588            // The default capture mode here is by-ref. Later on during upvar analysis,
1589            // we will force the captured arguments to by-move, but for async closures,
1590            // we want to make sure that we avoid unnecessarily moving captures, or else
1591            // all async closures would default to `FnOnce` as their calling mode.
1592            CaptureBy::Ref,
1593            closure_id,
1594            None,
1595            fn_decl_span,
1596            body_span,
1597            desugaring_kind,
1598            coroutine_source,
1599            mkbody,
1600        );
1601
1602        let expr = hir::Expr {
1603            hir_id: self.lower_node_id(closure_id),
1604            kind: coroutine_expr,
1605            span: self.lower_span(body_span),
1606        };
1607
1608        (self.arena.alloc_from_iter(parameters), expr)
1609    }
1610
1611    fn lower_method_sig(
1612        &mut self,
1613        generics: &Generics,
1614        sig: &FnSig,
1615        id: NodeId,
1616        kind: FnDeclKind,
1617        coroutine_kind: Option<CoroutineKind>,
1618        attrs: &[hir::Attribute],
1619    ) -> (&'hir hir::Generics<'hir>, hir::FnSig<'hir>) {
1620        let header = self.lower_fn_header(sig.header, hir::Safety::Safe, attrs);
1621        let itctx = ImplTraitContext::Universal;
1622        let (generics, decl) = self.lower_generics(generics, id, itctx, |this| {
1623            this.lower_fn_decl(&sig.decl, id, sig.span, kind, coroutine_kind)
1624        });
1625        (generics, hir::FnSig { header, decl, span: self.lower_span(sig.span) })
1626    }
1627
1628    pub(super) fn lower_fn_header(
1629        &mut self,
1630        h: FnHeader,
1631        default_safety: hir::Safety,
1632        attrs: &[hir::Attribute],
1633    ) -> hir::FnHeader {
1634        let asyncness = if let Some(CoroutineKind::Async { span, .. }) = h.coroutine_kind {
1635            hir::IsAsync::Async(self.lower_span(span))
1636        } else {
1637            hir::IsAsync::NotAsync
1638        };
1639
1640        let safety = self.lower_safety(h.safety, default_safety);
1641
1642        // Treat safe `#[target_feature]` functions as unsafe, but also remember that we did so.
1643        let safety = if find_attr!(attrs, AttributeKind::TargetFeature { was_forced: false, .. })
1644            && safety.is_safe()
1645            && !self.tcx.sess.target.is_like_wasm
1646        {
1647            hir::HeaderSafety::SafeTargetFeatures
1648        } else {
1649            safety.into()
1650        };
1651
1652        hir::FnHeader {
1653            safety,
1654            asyncness,
1655            constness: self.lower_constness(h.constness),
1656            abi: self.lower_extern(h.ext),
1657        }
1658    }
1659
1660    pub(super) fn lower_abi(&mut self, abi_str: StrLit) -> ExternAbi {
1661        let ast::StrLit { symbol_unescaped, span, .. } = abi_str;
1662        let extern_abi = symbol_unescaped.as_str().parse().unwrap_or_else(|_| {
1663            self.error_on_invalid_abi(abi_str);
1664            ExternAbi::Rust
1665        });
1666        let tcx = self.tcx;
1667
1668        // we can't do codegen for unsupported ABIs, so error now so we won't get farther
1669        if !tcx.sess.target.is_abi_supported(extern_abi) {
1670            let mut err = struct_span_code_err!(
1671                tcx.dcx(),
1672                span,
1673                E0570,
1674                "{extern_abi} is not a supported ABI for the current target",
1675            );
1676
1677            if let ExternAbi::Stdcall { unwind } = extern_abi {
1678                let c_abi = ExternAbi::C { unwind };
1679                let system_abi = ExternAbi::System { unwind };
1680                err.help(format!("if you need `extern {extern_abi}` on win32 and `extern {c_abi}` everywhere else, \
1681                    use `extern {system_abi}`"
1682                ));
1683            }
1684            err.emit();
1685        }
1686        // Show required feature gate even if we already errored, as the user is likely to build the code
1687        // for the actually intended target next and then they will need the feature gate.
1688        gate_unstable_abi(tcx.sess, tcx.features(), span, extern_abi);
1689        extern_abi
1690    }
1691
1692    pub(super) fn lower_extern(&mut self, ext: Extern) -> ExternAbi {
1693        match ext {
1694            Extern::None => ExternAbi::Rust,
1695            Extern::Implicit(_) => ExternAbi::FALLBACK,
1696            Extern::Explicit(abi, _) => self.lower_abi(abi),
1697        }
1698    }
1699
1700    fn error_on_invalid_abi(&self, abi: StrLit) {
1701        let abi_names = enabled_names(self.tcx.features(), abi.span)
1702            .iter()
1703            .map(|s| Symbol::intern(s))
1704            .collect::<Vec<_>>();
1705        let suggested_name = find_best_match_for_name(&abi_names, abi.symbol_unescaped, None);
1706        self.dcx().emit_err(InvalidAbi {
1707            abi: abi.symbol_unescaped,
1708            span: abi.span,
1709            suggestion: suggested_name.map(|suggested_name| InvalidAbiSuggestion {
1710                span: abi.span,
1711                suggestion: suggested_name.to_string(),
1712            }),
1713            command: "rustc --print=calling-conventions".to_string(),
1714        });
1715    }
1716
1717    pub(super) fn lower_constness(&mut self, c: Const) -> hir::Constness {
1718        match c {
1719            Const::Yes(_) => hir::Constness::Const,
1720            Const::No => hir::Constness::NotConst,
1721        }
1722    }
1723
1724    pub(super) fn lower_safety(&self, s: Safety, default: hir::Safety) -> hir::Safety {
1725        match s {
1726            Safety::Unsafe(_) => hir::Safety::Unsafe,
1727            Safety::Default => default,
1728            Safety::Safe(_) => hir::Safety::Safe,
1729        }
1730    }
1731
1732    /// Return the pair of the lowered `generics` as `hir::Generics` and the evaluation of `f` with
1733    /// the carried impl trait definitions and bounds.
1734    #[instrument(level = "debug", skip(self, f))]
1735    fn lower_generics<T>(
1736        &mut self,
1737        generics: &Generics,
1738        parent_node_id: NodeId,
1739        itctx: ImplTraitContext,
1740        f: impl FnOnce(&mut Self) -> T,
1741    ) -> (&'hir hir::Generics<'hir>, T) {
1742        assert!(self.impl_trait_defs.is_empty());
1743        assert!(self.impl_trait_bounds.is_empty());
1744
1745        let mut predicates: SmallVec<[hir::WherePredicate<'hir>; 4]> = SmallVec::new();
1746        predicates.extend(generics.params.iter().filter_map(|param| {
1747            self.lower_generic_bound_predicate(
1748                param.ident,
1749                param.id,
1750                &param.kind,
1751                &param.bounds,
1752                param.colon_span,
1753                generics.span,
1754                RelaxedBoundPolicy::Allowed,
1755                itctx,
1756                PredicateOrigin::GenericParam,
1757            )
1758        }));
1759        predicates.extend(
1760            generics
1761                .where_clause
1762                .predicates
1763                .iter()
1764                .map(|predicate| self.lower_where_predicate(predicate, &generics.params)),
1765        );
1766
1767        let mut params: SmallVec<[hir::GenericParam<'hir>; 4]> = self
1768            .lower_generic_params_mut(&generics.params, hir::GenericParamSource::Generics)
1769            .collect();
1770
1771        // Introduce extra lifetimes if late resolution tells us to.
1772        let extra_lifetimes = self.resolver.extra_lifetime_params(parent_node_id);
1773        params.extend(extra_lifetimes.into_iter().filter_map(|(ident, node_id, res)| {
1774            self.lifetime_res_to_generic_param(
1775                ident,
1776                node_id,
1777                res,
1778                hir::GenericParamSource::Generics,
1779            )
1780        }));
1781
1782        let has_where_clause_predicates = !generics.where_clause.predicates.is_empty();
1783        let where_clause_span = self.lower_span(generics.where_clause.span);
1784        let span = self.lower_span(generics.span);
1785        let res = f(self);
1786
1787        let impl_trait_defs = std::mem::take(&mut self.impl_trait_defs);
1788        params.extend(impl_trait_defs.into_iter());
1789
1790        let impl_trait_bounds = std::mem::take(&mut self.impl_trait_bounds);
1791        predicates.extend(impl_trait_bounds.into_iter());
1792
1793        let lowered_generics = self.arena.alloc(hir::Generics {
1794            params: self.arena.alloc_from_iter(params),
1795            predicates: self.arena.alloc_from_iter(predicates),
1796            has_where_clause_predicates,
1797            where_clause_span,
1798            span,
1799        });
1800
1801        (lowered_generics, res)
1802    }
1803
1804    pub(super) fn lower_define_opaque(
1805        &mut self,
1806        hir_id: HirId,
1807        define_opaque: &Option<ThinVec<(NodeId, Path)>>,
1808    ) {
1809        assert_eq!(self.define_opaque, None);
1810        assert!(hir_id.is_owner());
1811        let Some(define_opaque) = define_opaque.as_ref() else {
1812            return;
1813        };
1814        let define_opaque = define_opaque.iter().filter_map(|(id, path)| {
1815            let res = self.resolver.get_partial_res(*id);
1816            let Some(did) = res.and_then(|res| res.expect_full_res().opt_def_id()) else {
1817                self.dcx().span_delayed_bug(path.span, "should have errored in resolve");
1818                return None;
1819            };
1820            let Some(did) = did.as_local() else {
1821                self.dcx().span_err(
1822                    path.span,
1823                    "only opaque types defined in the local crate can be defined",
1824                );
1825                return None;
1826            };
1827            Some((self.lower_span(path.span), did))
1828        });
1829        let define_opaque = self.arena.alloc_from_iter(define_opaque);
1830        self.define_opaque = Some(define_opaque);
1831    }
1832
1833    pub(super) fn lower_generic_bound_predicate(
1834        &mut self,
1835        ident: Ident,
1836        id: NodeId,
1837        kind: &GenericParamKind,
1838        bounds: &[GenericBound],
1839        colon_span: Option<Span>,
1840        parent_span: Span,
1841        rbp: RelaxedBoundPolicy<'_>,
1842        itctx: ImplTraitContext,
1843        origin: PredicateOrigin,
1844    ) -> Option<hir::WherePredicate<'hir>> {
1845        // Do not create a clause if we do not have anything inside it.
1846        if bounds.is_empty() {
1847            return None;
1848        }
1849
1850        let bounds = self.lower_param_bounds(bounds, rbp, itctx);
1851
1852        let param_span = ident.span;
1853
1854        // Reconstruct the span of the entire predicate from the individual generic bounds.
1855        let span_start = colon_span.unwrap_or_else(|| param_span.shrink_to_hi());
1856        let span = bounds.iter().fold(span_start, |span_accum, bound| {
1857            match bound.span().find_ancestor_inside(parent_span) {
1858                Some(bound_span) => span_accum.to(bound_span),
1859                None => span_accum,
1860            }
1861        });
1862        let span = self.lower_span(span);
1863        let hir_id = self.next_id();
1864        let kind = self.arena.alloc(match kind {
1865            GenericParamKind::Const { .. } => return None,
1866            GenericParamKind::Type { .. } => {
1867                let def_id = self.local_def_id(id).to_def_id();
1868                let hir_id = self.next_id();
1869                let res = Res::Def(DefKind::TyParam, def_id);
1870                let ident = self.lower_ident(ident);
1871                let ty_path = self.arena.alloc(hir::Path {
1872                    span: self.lower_span(param_span),
1873                    res,
1874                    segments: self
1875                        .arena
1876                        .alloc_from_iter([hir::PathSegment::new(ident, hir_id, res)]),
1877                });
1878                let ty_id = self.next_id();
1879                let bounded_ty =
1880                    self.ty_path(ty_id, param_span, hir::QPath::Resolved(None, ty_path));
1881                hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
1882                    bounded_ty: self.arena.alloc(bounded_ty),
1883                    bounds,
1884                    bound_generic_params: &[],
1885                    origin,
1886                })
1887            }
1888            GenericParamKind::Lifetime => {
1889                let lt_id = self.next_node_id();
1890                let lifetime =
1891                    self.new_named_lifetime(id, lt_id, ident, LifetimeSource::Other, ident.into());
1892                hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
1893                    lifetime,
1894                    bounds,
1895                    in_where_clause: false,
1896                })
1897            }
1898        });
1899        Some(hir::WherePredicate { hir_id, span, kind })
1900    }
1901
1902    fn lower_where_predicate(
1903        &mut self,
1904        pred: &WherePredicate,
1905        params: &[ast::GenericParam],
1906    ) -> hir::WherePredicate<'hir> {
1907        let hir_id = self.lower_node_id(pred.id);
1908        let span = self.lower_span(pred.span);
1909        self.lower_attrs(hir_id, &pred.attrs, span, Target::WherePredicate);
1910        let kind = self.arena.alloc(match &pred.kind {
1911            WherePredicateKind::BoundPredicate(WhereBoundPredicate {
1912                bound_generic_params,
1913                bounded_ty,
1914                bounds,
1915            }) => {
1916                let rbp = if bound_generic_params.is_empty() {
1917                    RelaxedBoundPolicy::AllowedIfOnTyParam(bounded_ty.id, params)
1918                } else {
1919                    RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::LateBoundVarsInScope)
1920                };
1921                hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate {
1922                    bound_generic_params: self.lower_generic_params(
1923                        bound_generic_params,
1924                        hir::GenericParamSource::Binder,
1925                    ),
1926                    bounded_ty: self.lower_ty_alloc(
1927                        bounded_ty,
1928                        ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
1929                    ),
1930                    bounds: self.lower_param_bounds(
1931                        bounds,
1932                        rbp,
1933                        ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
1934                    ),
1935                    origin: PredicateOrigin::WhereClause,
1936                })
1937            }
1938            WherePredicateKind::RegionPredicate(WhereRegionPredicate { lifetime, bounds }) => {
1939                hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate {
1940                    lifetime: self.lower_lifetime(
1941                        lifetime,
1942                        LifetimeSource::Other,
1943                        lifetime.ident.into(),
1944                    ),
1945                    bounds: self.lower_param_bounds(
1946                        bounds,
1947                        RelaxedBoundPolicy::Allowed,
1948                        ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
1949                    ),
1950                    in_where_clause: true,
1951                })
1952            }
1953            WherePredicateKind::EqPredicate(WhereEqPredicate { lhs_ty, rhs_ty }) => {
1954                hir::WherePredicateKind::EqPredicate(hir::WhereEqPredicate {
1955                    lhs_ty: self.lower_ty_alloc(
1956                        lhs_ty,
1957                        ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
1958                    ),
1959                    rhs_ty: self.lower_ty_alloc(
1960                        rhs_ty,
1961                        ImplTraitContext::Disallowed(ImplTraitPosition::Bound),
1962                    ),
1963                })
1964            }
1965        });
1966        hir::WherePredicate { hir_id, span, kind }
1967    }
1968}