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