rustc_ast_lowering/
item.rs

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