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