rustc_ast_lowering/
item.rs

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