Skip to main content

rustdoc/clean/
mod.rs

1//! This module defines the primary IR[^1] used in rustdoc together with the procedures that
2//! transform rustc data types into it.
3//!
4//! This IR — commonly referred to as the *cleaned AST* — is modeled after the [AST][rustc_ast].
5//!
6//! There are two kinds of transformation — *cleaning* — procedures:
7//!
8//! 1. Cleans [HIR][hir] types. Used for user-written code and inlined local re-exports
9//!    both found in the local crate.
10//! 2. Cleans [`rustc_middle::ty`] types. Used for inlined cross-crate re-exports and anything
11//!    output by the trait solver (e.g., when synthesizing blanket and auto-trait impls).
12//!    They usually have `ty` or `middle` in their name.
13//!
14//! Their name is prefixed by `clean_`.
15//!
16//! Both the HIR and the `rustc_middle::ty` IR are quite removed from the source code.
17//! The cleaned AST on the other hand is closer to it which simplifies the rendering process.
18//! Furthermore, operating on a single IR instead of two avoids duplicating efforts down the line.
19//!
20//! This IR is consumed by both the HTML and the JSON backend.
21//!
22//! [^1]: Intermediate representation.
23
24mod auto_trait;
25mod blanket_impl;
26pub(crate) mod cfg;
27pub(crate) mod inline;
28mod render_macro_matchers;
29mod simplify;
30pub(crate) mod types;
31pub(crate) mod utils;
32
33use std::borrow::Cow;
34use std::collections::BTreeMap;
35use std::mem;
36
37use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet, IndexEntry};
38use rustc_data_structures::thin_vec::ThinVec;
39use rustc_errors::codes::*;
40use rustc_errors::{FatalError, struct_span_code_err};
41use rustc_hir as hir;
42use rustc_hir::attrs::lang_items::LangItem;
43use rustc_hir::attrs::{AttributeKind, DocAttribute, DocInline};
44use rustc_hir::def::{CtorKind, DefKind, MacroKinds, Res};
45use rustc_hir::def_id::{DefId, DefIdMap, DefIdSet, LOCAL_CRATE, LocalDefId};
46use rustc_hir::{PredicateOrigin, find_attr};
47use rustc_hir_analysis::{lower_const_arg_for_rustdoc, lower_ty};
48use rustc_middle::metadata::Reexport;
49use rustc_middle::middle::resolve_bound_vars as rbv;
50use rustc_middle::ty::{
51    self, AdtKind, GenericArgsRef, RegionExt, Ty, TyCtxt, TypeVisitableExt, TypingMode,
52    Unnormalized,
53};
54use rustc_middle::{bug, span_bug};
55use rustc_span::ExpnKind;
56use rustc_span::hygiene::{AstPass, MacroKind};
57use rustc_span::symbol::{Ident, Symbol, kw};
58use rustc_trait_selection::traits::wf::object_region_bounds;
59use tracing::{debug, instrument};
60use utils::*;
61
62pub(crate) use self::cfg::{CfgInfo, extract_cfg_from_attrs};
63pub(crate) use self::types::*;
64pub(crate) use self::utils::{krate, register_res, synthesize_auto_trait_and_blanket_impls};
65use crate::core::DocContext;
66use crate::formats::item_type::ItemType;
67use crate::visit_ast;
68
69pub(crate) fn clean_doc_module<'tcx>(
70    doc: &visit_ast::Module<'tcx>,
71    cx: &mut DocContext<'tcx>,
72) -> Item {
73    let mut items: Vec<Item> = vec![];
74    let mut inserted = FxHashSet::default();
75    items.extend(doc.foreigns.iter().map(|visit_ast::Foreign { item, renamed, import_id }| {
76        let item = clean_maybe_renamed_foreign_item(cx, item, *renamed, *import_id);
77        if let Some(name) = item.name
78            && (cx.document_hidden() || !item.is_doc_hidden())
79        {
80            inserted.insert((item.type_(), name));
81        }
82        item
83    }));
84    items.extend(doc.mods.iter().filter_map(|x| {
85        if !inserted.insert((ItemType::Module, x.name)) {
86            return None;
87        }
88        let item = clean_doc_module(x, cx);
89        if !cx.document_hidden() && item.is_doc_hidden() {
90            // Hidden modules are stripped at a later stage.
91            // If a hidden module has the same name as a visible one, we want
92            // to keep both of them around.
93            inserted.remove(&(ItemType::Module, x.name));
94        }
95        Some(item)
96    }));
97
98    // Split up glob imports from all other items.
99    //
100    // This covers the case where somebody does an import which should pull in an item,
101    // but there's already an item with the same namespace and same name. Rust gives
102    // priority to the not-imported one, so we should, too.
103    items.extend(doc.items.values().flat_map(
104        |visit_ast::ItemEntry { item, renamed, import_ids }| {
105            // First, lower everything other than glob imports.
106            if matches!(item.kind, hir::ItemKind::Use(_, hir::UseKind::Glob)) {
107                return Vec::new();
108            }
109            let v = clean_maybe_renamed_item(cx, item, *renamed, import_ids);
110            for item in &v {
111                if let Some(name) = item.name
112                    && (cx.document_hidden() || !item.is_doc_hidden())
113                {
114                    inserted.insert((item.type_(), name));
115                }
116            }
117            v
118        },
119    ));
120    items.extend(doc.inlined_foreigns.iter().flat_map(
121        |((_, renamed), visit_ast::InlinedForeign { res, import_id })| {
122            let Some(def_id) = res.opt_def_id() else { return Vec::new() };
123            let name = renamed.unwrap_or_else(|| cx.tcx.item_name(def_id));
124            let import = cx.tcx.hir_expect_item(*import_id);
125            match import.kind {
126                hir::ItemKind::Use(path, kind) => {
127                    let hir::UsePath { segments, span, .. } = *path;
128                    let path = hir::Path { segments, res: *res, span };
129                    clean_use_statement_inner(
130                        import,
131                        Some(name),
132                        &path,
133                        kind,
134                        cx,
135                        &mut Default::default(),
136                    )
137                }
138                _ => unreachable!(),
139            }
140        },
141    ));
142    items.extend(doc.items.values().flat_map(
143        |visit_ast::ItemEntry { item, renamed, import_ids: _ }| {
144            // Now we actually lower the imports, skipping everything else.
145            if let hir::ItemKind::Use(path, hir::UseKind::Glob) = item.kind {
146                clean_use_statement(item, *renamed, path, hir::UseKind::Glob, cx, &mut inserted)
147            } else {
148                // skip everything else
149                Vec::new()
150            }
151        },
152    ));
153
154    // determine if we should display the inner contents or
155    // the outer `mod` item for the source code.
156
157    let span = Span::new({
158        let where_outer = doc.where_outer(cx.tcx);
159        let sm = cx.sess().source_map();
160        let outer = sm.lookup_char_pos(where_outer.lo());
161        let inner = sm.lookup_char_pos(doc.where_inner.lo());
162        if outer.file.start_pos == inner.file.start_pos {
163            // mod foo { ... }
164            where_outer
165        } else {
166            // mod foo; (and a separate SourceFile for the contents)
167            doc.where_inner
168        }
169    });
170
171    let kind = ModuleItem(Module { items, span });
172    generate_item_with_correct_attrs(
173        cx,
174        kind,
175        doc.def_id.to_def_id(),
176        doc.name,
177        doc.import_id.as_slice(),
178        doc.renamed,
179    )
180}
181
182fn is_glob_import(tcx: TyCtxt<'_>, import_id: LocalDefId) -> bool {
183    if let hir::Node::Item(item) = tcx.hir_node_by_def_id(import_id)
184        && let hir::ItemKind::Use(_, use_kind) = item.kind
185    {
186        use_kind == hir::UseKind::Glob
187    } else {
188        false
189    }
190}
191
192/// Returns true if `def_id` is a macro and should be inlined.
193pub(crate) fn macro_reexport_is_inline(
194    tcx: TyCtxt<'_>,
195    import_id: LocalDefId,
196    def_id: DefId,
197) -> bool {
198    if !matches!(tcx.def_kind(def_id), DefKind::Macro(MacroKinds::BANG)) {
199        return false;
200    }
201
202    for reexport_def_id in reexport_chain(tcx, import_id, def_id).iter().flat_map(|r| r.id()) {
203        let is_hidden = tcx.is_doc_hidden(reexport_def_id);
204        let is_inline = find_attr!(
205            inline::load_attrs(tcx, reexport_def_id),
206            Doc(d)
207            if d.inline.first().is_some_and(|(inline, _)| *inline == DocInline::Inline)
208        );
209
210        // hidden takes absolute priority over inline on the same node
211        if is_hidden {
212            return false;
213        }
214        if is_inline {
215            return true;
216        }
217    }
218    false
219}
220
221fn generate_item_with_correct_attrs(
222    cx: &mut DocContext<'_>,
223    kind: ItemKind,
224    def_id: DefId,
225    name: Symbol,
226    import_ids: &[LocalDefId],
227    renamed: Option<Symbol>,
228) -> Item {
229    let tcx = cx.tcx;
230    let target_attrs = inline::load_attrs(tcx, def_id);
231    let attrs = if !import_ids.is_empty() {
232        let mut attrs = Vec::with_capacity(import_ids.len());
233        let mut is_inline = false;
234
235        for import_id in import_ids.iter().copied() {
236            // glob reexports are treated the same as `#[doc(inline)]` items.
237            //
238            // For glob re-exports the item may or may not exist to be re-exported (potentially the
239            // cfgs on the path up until the glob can be removed, and only cfgs on the globbed item
240            // itself matter), for non-inlined re-exports see #85043.
241            let import_is_inline = find_attr!(
242                inline::load_attrs(tcx, import_id.to_def_id()),
243                Doc(d)
244                if d.inline.first().is_some_and(|(inline, _)| *inline == DocInline::Inline)
245            ) || (is_glob_import(tcx, import_id)
246                && (cx.document_hidden() || !tcx.is_doc_hidden(def_id)))
247                || macro_reexport_is_inline(tcx, import_id, def_id);
248            is_inline = is_inline || import_is_inline;
249            attrs.extend(get_all_import_attributes(cx, import_id, def_id, is_inline));
250        }
251        let keep_target_cfg = is_inline || matches!(kind, ItemKind::TypeAliasItem(..));
252        add_without_unwanted_attributes(&mut attrs, target_attrs, keep_target_cfg, None);
253        attrs
254    } else {
255        // We only keep the item's attributes.
256        target_attrs.iter().map(|attr| (Cow::Borrowed(attr), None)).collect()
257    };
258    let attrs = Attributes::from_hir_iter(attrs.iter().map(|(attr, did)| (&**attr, *did)), false);
259
260    let name = renamed.or(Some(name));
261    let mut item = Item::from_def_id_and_attrs_and_parts(def_id, name, kind, attrs, None);
262    // FIXME (GuillaumeGomez): Should we also make `inline_stmt_id` a `Vec` instead of an `Option`?
263    item.inner.inline_stmt_id = import_ids.first().copied();
264    item
265}
266
267fn clean_generic_bound<'tcx>(
268    bound: &hir::GenericBound<'tcx>,
269    cx: &mut DocContext<'tcx>,
270) -> Option<GenericBound> {
271    Some(match bound {
272        hir::GenericBound::Outlives(lt) => GenericBound::Outlives(clean_lifetime(lt, cx)),
273        hir::GenericBound::Trait(t) => {
274            // `T: [const] Destruct` is hidden because `T: Destruct` is a no-op.
275            if let hir::BoundConstness::Maybe(_) = t.modifiers.constness
276                && cx.tcx.lang_items().destruct_trait() == Some(t.trait_ref.trait_def_id().unwrap())
277            {
278                return None;
279            }
280
281            GenericBound::TraitBound(clean_poly_trait_ref(t, cx), t.modifiers)
282        }
283        hir::GenericBound::Use(args, ..) => {
284            GenericBound::Use(args.iter().map(|arg| clean_precise_capturing_arg(arg, cx)).collect())
285        }
286    })
287}
288
289pub(crate) fn clean_trait_ref_with_constraints<'tcx>(
290    cx: &mut DocContext<'tcx>,
291    trait_ref: ty::PolyTraitRef<'tcx>,
292    constraints: ThinVec<AssocItemConstraint>,
293) -> Path {
294    let kind = ItemType::from_def_id(trait_ref.def_id(), cx.tcx);
295    if !matches!(kind, ItemType::Trait | ItemType::TraitAlias) {
296        span_bug!(cx.tcx.def_span(trait_ref.def_id()), "`TraitRef` had unexpected kind {kind:?}");
297    }
298    inline::record_extern_fqn(cx, trait_ref.def_id(), kind);
299    let path = clean_middle_path(
300        cx,
301        trait_ref.def_id(),
302        true,
303        constraints,
304        trait_ref.map_bound(|tr| tr.args),
305    );
306
307    debug!(?trait_ref);
308
309    path
310}
311
312fn clean_poly_trait_ref_with_constraints<'tcx>(
313    cx: &mut DocContext<'tcx>,
314    poly_trait_ref: ty::PolyTraitRef<'tcx>,
315    constraints: ThinVec<AssocItemConstraint>,
316) -> GenericBound {
317    GenericBound::TraitBound(
318        PolyTrait {
319            trait_: clean_trait_ref_with_constraints(cx, poly_trait_ref, constraints),
320            generic_params: clean_bound_vars(poly_trait_ref.bound_vars(), cx.tcx),
321        },
322        hir::TraitBoundModifiers::NONE,
323    )
324}
325
326fn clean_lifetime(lifetime: &hir::Lifetime, cx: &DocContext<'_>) -> Lifetime {
327    if let Some(
328        rbv::ResolvedArg::EarlyBound(did)
329        | rbv::ResolvedArg::LateBound(_, _, did)
330        | rbv::ResolvedArg::Free(_, did),
331    ) = cx.tcx.named_bound_var(lifetime.hir_id)
332        && let Some(lt) = cx.args.get(&did.to_def_id()).and_then(|arg| arg.as_lt())
333    {
334        return *lt;
335    }
336    Lifetime(lifetime.ident.name)
337}
338
339pub(crate) fn clean_precise_capturing_arg(
340    arg: &hir::PreciseCapturingArg<'_>,
341    cx: &DocContext<'_>,
342) -> PreciseCapturingArg {
343    match arg {
344        hir::PreciseCapturingArg::Lifetime(lt) => {
345            PreciseCapturingArg::Lifetime(clean_lifetime(lt, cx))
346        }
347        hir::PreciseCapturingArg::Param(param) => PreciseCapturingArg::Param(param.ident.name),
348    }
349}
350
351pub(crate) fn clean_const_item_rhs<'tcx>(
352    ct_rhs: hir::ConstItemRhs<'tcx>,
353    parent: DefId,
354) -> ConstantKind {
355    match ct_rhs {
356        hir::ConstItemRhs::Body(body) => ConstantKind::Local { def_id: parent, body },
357        hir::ConstItemRhs::TypeConst(ct) => clean_const(ct),
358    }
359}
360
361pub(crate) fn clean_const<'tcx>(constant: &hir::ConstArg<'tcx>) -> ConstantKind {
362    match &constant.kind {
363        hir::ConstArgKind::Path(qpath) => {
364            ConstantKind::Path { path: qpath_to_string(qpath).into() }
365        }
366        hir::ConstArgKind::Struct(..) => {
367            // FIXME(mgca): proper printing :3
368            ConstantKind::Path { path: "/* STRUCT EXPR */".to_string().into() }
369        }
370        hir::ConstArgKind::TupleCall(..) => {
371            ConstantKind::Path { path: "/* TUPLE CALL */".to_string().into() }
372        }
373        hir::ConstArgKind::Tup(..) => {
374            // FIXME(mgca): proper printing :3
375            ConstantKind::Path { path: "/* TUPLE EXPR */".to_string().into() }
376        }
377        hir::ConstArgKind::Array(..) => {
378            ConstantKind::Path { path: "/* ARRAY EXPR */".to_string().into() }
379        }
380        hir::ConstArgKind::Anon(anon) => ConstantKind::Anonymous { body: anon.body },
381        hir::ConstArgKind::Infer(..) | hir::ConstArgKind::Error(..) => ConstantKind::Infer,
382        hir::ConstArgKind::Literal { .. } => {
383            ConstantKind::Path { path: "/* LITERAL */".to_string().into() }
384        }
385    }
386}
387
388pub(crate) fn clean_middle_const<'tcx>(
389    constant: ty::Binder<'tcx, ty::Const<'tcx>>,
390) -> ConstantKind {
391    // FIXME: instead of storing the stringified expression, store `self` directly instead.
392    ConstantKind::TyConst { expr: constant.skip_binder().to_string().into() }
393}
394
395pub(crate) fn clean_middle_region<'tcx>(
396    region: ty::Region<'tcx>,
397    tcx: TyCtxt<'tcx>,
398) -> Option<Lifetime> {
399    region.get_name(tcx).map(Lifetime)
400}
401
402fn clean_where_predicate<'tcx>(
403    predicate: &hir::WherePredicate<'tcx>,
404    cx: &mut DocContext<'tcx>,
405) -> Option<WherePredicate> {
406    if !predicate.kind.in_where_clause() {
407        return None;
408    }
409    Some(match predicate.kind {
410        hir::WherePredicateKind::BoundPredicate(wbp) => {
411            let bound_params = wbp
412                .bound_generic_params
413                .iter()
414                .map(|param| clean_generic_param(cx, None, param))
415                .collect();
416            WherePredicate::BoundPredicate {
417                ty: clean_ty(wbp.bounded_ty, cx),
418                bounds: wbp.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
419                bound_params,
420            }
421        }
422        hir::WherePredicateKind::RegionPredicate(wrp) => WherePredicate::RegionPredicate {
423            lifetime: clean_lifetime(wrp.lifetime, cx),
424            bounds: wrp.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
425        },
426    })
427}
428
429pub(crate) fn clean_clause<'tcx>(
430    clause: ty::Clause<'tcx>,
431    cx: &mut DocContext<'tcx>,
432) -> Option<WherePredicate> {
433    let bound_clause = clause.kind();
434    match bound_clause.skip_binder() {
435        ty::ClauseKind::Trait(pred) => clean_poly_trait_predicate(bound_clause.rebind(pred), cx),
436        ty::ClauseKind::RegionOutlives(pred) => Some(clean_region_outlives_clause(pred, cx.tcx)),
437        ty::ClauseKind::TypeOutlives(pred) => {
438            Some(clean_type_outlives_clause(bound_clause.rebind(pred), cx))
439        }
440        ty::ClauseKind::Projection(pred) => {
441            Some(clean_projection_predicate(bound_clause.rebind(pred), cx))
442        }
443        // FIXME(generic_const_exprs): should this do something?
444        ty::ClauseKind::ConstEvaluatable(..)
445        | ty::ClauseKind::WellFormed(..)
446        | ty::ClauseKind::ConstArgHasType(..)
447        | ty::ClauseKind::UnstableFeature(..)
448        // FIXME(const_trait_impl): We can probably use this `HostEffect` pred to render `~const`.
449        | ty::ClauseKind::HostEffect(_) => None,
450    }
451}
452
453fn clean_poly_trait_predicate<'tcx>(
454    pred: ty::PolyTraitPredicate<'tcx>,
455    cx: &mut DocContext<'tcx>,
456) -> Option<WherePredicate> {
457    // `T: [const] Destruct` is hidden because `T: Destruct` is a no-op.
458    // FIXME(const_trait_impl) check constness
459    if Some(pred.skip_binder().def_id()) == cx.tcx.lang_items().destruct_trait() {
460        return None;
461    }
462
463    let poly_trait_ref = pred.map_bound(|pred| pred.trait_ref);
464    Some(WherePredicate::BoundPredicate {
465        ty: clean_middle_ty(poly_trait_ref.self_ty(), cx, None, None),
466        bounds: vec![clean_poly_trait_ref_with_constraints(cx, poly_trait_ref, ThinVec::new())],
467        bound_params: Vec::new(),
468    })
469}
470
471fn clean_region_outlives_clause<'tcx>(
472    clause: ty::RegionOutlivesClause<'tcx>,
473    tcx: TyCtxt<'tcx>,
474) -> WherePredicate {
475    let ty::OutlivesClause(a, b) = clause;
476
477    WherePredicate::RegionPredicate {
478        lifetime: clean_middle_region(a, tcx).expect("failed to clean lifetime"),
479        bounds: vec![GenericBound::Outlives(
480            clean_middle_region(b, tcx).expect("failed to clean bounds"),
481        )],
482    }
483}
484
485fn clean_type_outlives_clause<'tcx>(
486    clause: ty::Binder<'tcx, ty::TypeOutlivesClause<'tcx>>,
487    cx: &mut DocContext<'tcx>,
488) -> WherePredicate {
489    let ty::OutlivesClause(ty, lt) = clause.skip_binder();
490
491    WherePredicate::BoundPredicate {
492        ty: clean_middle_ty(clause.rebind(ty), cx, None, None),
493        bounds: vec![GenericBound::Outlives(
494            clean_middle_region(lt, cx.tcx).expect("failed to clean lifetimes"),
495        )],
496        bound_params: Vec::new(),
497    }
498}
499
500fn clean_middle_term<'tcx>(
501    term: ty::Binder<'tcx, ty::Term<'tcx>>,
502    cx: &mut DocContext<'tcx>,
503) -> Term {
504    match term.skip_binder().kind() {
505        ty::TermKind::Ty(ty) => Term::Type(clean_middle_ty(term.rebind(ty), cx, None, None)),
506        ty::TermKind::Const(c) => Term::Constant(clean_middle_const(term.rebind(c))),
507    }
508}
509
510fn clean_hir_term<'tcx>(
511    assoc_item: Option<DefId>,
512    term: &hir::Term<'tcx>,
513    cx: &mut DocContext<'tcx>,
514) -> Term {
515    match term {
516        hir::Term::Ty(ty) => Term::Type(clean_ty(ty, cx)),
517        hir::Term::Const(c) => {
518            // FIXME(generic_const_items): this should instantiate with the alias item's args
519            let ty = cx.tcx.type_of(assoc_item.unwrap()).instantiate_identity().skip_norm_wip();
520            let ct = lower_const_arg_for_rustdoc(cx.tcx, c, ty);
521            Term::Constant(clean_middle_const(ty::Binder::dummy(ct)))
522        }
523    }
524}
525
526fn clean_projection_predicate<'tcx>(
527    pred: ty::Binder<'tcx, ty::ProjectionPredicate<'tcx>>,
528    cx: &mut DocContext<'tcx>,
529) -> WherePredicate {
530    WherePredicate::ProjectionPredicate {
531        lhs: clean_projection(pred.map_bound(|p| p.projection_term), cx, None),
532        rhs: clean_middle_term(pred.map_bound(|p| p.term), cx),
533    }
534}
535
536fn clean_projection<'tcx>(
537    proj: ty::Binder<'tcx, ty::AliasTerm<'tcx>>,
538    cx: &mut DocContext<'tcx>,
539    parent_def_id: Option<DefId>,
540) -> QPathData {
541    let trait_ = clean_trait_ref_with_constraints(
542        cx,
543        proj.map_bound(|proj| proj.trait_ref(cx.tcx)),
544        ThinVec::new(),
545    );
546    let self_type = clean_middle_ty(proj.map_bound(|proj| proj.self_ty()), cx, None, None);
547    let self_def_id = match parent_def_id {
548        Some(parent_def_id) => cx.tcx.opt_parent(parent_def_id).or(Some(parent_def_id)),
549        None => self_type.def_id(&cx.cache),
550    };
551    let should_fully_qualify = should_fully_qualify_path(self_def_id, &trait_, &self_type);
552
553    QPathData {
554        assoc: projection_to_path_segment(proj, cx),
555        self_type,
556        should_fully_qualify,
557        trait_: Some(trait_),
558    }
559}
560
561fn should_fully_qualify_path(self_def_id: Option<DefId>, trait_: &Path, self_type: &Type) -> bool {
562    !trait_.segments.is_empty()
563        && self_def_id
564            .zip(Some(trait_.def_id()))
565            .map_or(!self_type.is_self_type(), |(id, trait_)| id != trait_)
566}
567
568fn projection_to_path_segment<'tcx>(
569    proj: ty::Binder<'tcx, ty::AliasTerm<'tcx>>,
570    cx: &mut DocContext<'tcx>,
571) -> PathSegment {
572    let def_id = proj.skip_binder().expect_projection_def_id();
573    let generics = cx.tcx.generics_of(def_id);
574    PathSegment {
575        name: cx.tcx.item_name(def_id),
576        args: GenericArgs::AngleBracketed {
577            args: clean_middle_generic_args(
578                cx,
579                proj.map_bound(|ty| &ty.args[generics.parent_count..]),
580                false,
581                def_id,
582            ),
583            constraints: Default::default(),
584        },
585    }
586}
587
588fn clean_generic_param_def(
589    def: &ty::GenericParamDef,
590    defaults: ParamDefaults,
591    cx: &mut DocContext<'_>,
592) -> GenericParamDef {
593    let (name, kind) = match def.kind {
594        ty::GenericParamDefKind::Lifetime => {
595            (def.name, GenericParamDefKind::Lifetime { outlives: ThinVec::new() })
596        }
597        ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
598            let default = if let ParamDefaults::Yes = defaults
599                && has_default
600            {
601                Some(clean_middle_ty(
602                    ty::Binder::dummy(
603                        cx.tcx.type_of(def.def_id).instantiate_identity().skip_norm_wip(),
604                    ),
605                    cx,
606                    Some(def.def_id),
607                    None,
608                ))
609            } else {
610                None
611            };
612            (
613                def.name,
614                GenericParamDefKind::Type {
615                    bounds: ThinVec::new(), // These are filled in from the where-clauses.
616                    default: default.map(Box::new),
617                    synthetic,
618                },
619            )
620        }
621        ty::GenericParamDefKind::Const { has_default } => (
622            def.name,
623            GenericParamDefKind::Const {
624                ty: Box::new(clean_middle_ty(
625                    ty::Binder::dummy(
626                        cx.tcx.type_of(def.def_id).instantiate_identity().skip_norm_wip(),
627                    ),
628                    cx,
629                    Some(def.def_id),
630                    None,
631                )),
632                default: if let ParamDefaults::Yes = defaults
633                    && has_default
634                {
635                    Some(Box::new(
636                        cx.tcx
637                            .const_param_default(def.def_id)
638                            .instantiate_identity()
639                            .skip_norm_wip()
640                            .to_string(),
641                    ))
642                } else {
643                    None
644                },
645            },
646        ),
647    };
648
649    GenericParamDef { name, def_id: def.def_id, kind }
650}
651
652/// Whether to clean generic parameter defaults or not.
653enum ParamDefaults {
654    Yes,
655    No,
656}
657
658fn clean_generic_param<'tcx>(
659    cx: &mut DocContext<'tcx>,
660    generics: Option<&hir::Generics<'tcx>>,
661    param: &hir::GenericParam<'tcx>,
662) -> GenericParamDef {
663    let (name, kind) = match param.kind {
664        hir::GenericParamKind::Lifetime { .. } => {
665            let outlives = if let Some(generics) = generics {
666                generics
667                    .outlives_for_param(param.def_id)
668                    .filter(|bp| !bp.in_where_clause)
669                    .flat_map(|bp| bp.bounds)
670                    .map(|bound| match bound {
671                        hir::GenericBound::Outlives(lt) => clean_lifetime(lt, cx),
672                        _ => panic!(),
673                    })
674                    .collect()
675            } else {
676                ThinVec::new()
677            };
678            (param.name.ident().name, GenericParamDefKind::Lifetime { outlives })
679        }
680        hir::GenericParamKind::Type { ref default, synthetic } => {
681            let bounds = if let Some(generics) = generics {
682                generics
683                    .bounds_for_param(param.def_id)
684                    .filter(|bp| bp.origin != PredicateOrigin::WhereClause)
685                    .flat_map(|bp| bp.bounds)
686                    .filter_map(|x| clean_generic_bound(x, cx))
687                    .collect()
688            } else {
689                ThinVec::new()
690            };
691            (
692                param.name.ident().name,
693                GenericParamDefKind::Type {
694                    bounds,
695                    default: default.map(|t| clean_ty(t, cx)).map(Box::new),
696                    synthetic,
697                },
698            )
699        }
700        hir::GenericParamKind::Const { ty, default } => (
701            param.name.ident().name,
702            GenericParamDefKind::Const {
703                ty: Box::new(clean_ty(ty, cx)),
704                default: default.map(|ct| {
705                    Box::new(
706                        lower_const_arg_for_rustdoc(cx.tcx, ct, lower_ty(cx.tcx, ty)).to_string(),
707                    )
708                }),
709            },
710        ),
711    };
712
713    GenericParamDef { name, def_id: param.def_id.to_def_id(), kind }
714}
715
716/// Synthetic type-parameters are inserted after normal ones.
717/// In order for normal parameters to be able to refer to synthetic ones,
718/// scans them first.
719fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
720    match param.kind {
721        hir::GenericParamKind::Type { synthetic, .. } => synthetic,
722        _ => false,
723    }
724}
725
726/// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
727///
728/// See `lifetime_to_generic_param` in `rustc_ast_lowering` for more information.
729fn is_elided_lifetime(param: &hir::GenericParam<'_>) -> bool {
730    matches!(
731        param.kind,
732        hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided(_) }
733    )
734}
735
736pub(crate) fn clean_generics<'tcx>(
737    gens: &hir::Generics<'tcx>,
738    cx: &mut DocContext<'tcx>,
739) -> Generics {
740    let impl_trait_params = gens
741        .params
742        .iter()
743        .filter(|param| is_impl_trait(param))
744        .map(|param| {
745            let param = clean_generic_param(cx, Some(gens), param);
746            match param.kind {
747                GenericParamDefKind::Lifetime { .. } => unreachable!(),
748                GenericParamDefKind::Type { ref bounds, .. } => {
749                    cx.impl_trait_bounds.insert(param.def_id.into(), bounds.to_vec());
750                }
751                GenericParamDefKind::Const { .. } => unreachable!(),
752            }
753            param
754        })
755        .collect::<Vec<_>>();
756
757    let mut bound_predicates = FxIndexMap::default();
758    let mut region_predicates = FxIndexMap::default();
759    let mut eq_predicates = ThinVec::default();
760    for pred in gens.predicates.iter().filter_map(|x| clean_where_predicate(x, cx)) {
761        match pred {
762            WherePredicate::BoundPredicate { ty, bounds, bound_params } => {
763                match bound_predicates.entry(ty) {
764                    IndexEntry::Vacant(v) => {
765                        v.insert((bounds, bound_params));
766                    }
767                    IndexEntry::Occupied(mut o) => {
768                        // we merge both bounds.
769                        for bound in bounds {
770                            if !o.get().0.contains(&bound) {
771                                o.get_mut().0.push(bound);
772                            }
773                        }
774                        for bound_param in bound_params {
775                            if !o.get().1.contains(&bound_param) {
776                                o.get_mut().1.push(bound_param);
777                            }
778                        }
779                    }
780                }
781            }
782            WherePredicate::RegionPredicate { lifetime, bounds } => {
783                match region_predicates.entry(lifetime) {
784                    IndexEntry::Vacant(v) => {
785                        v.insert(bounds);
786                    }
787                    IndexEntry::Occupied(mut o) => {
788                        // we merge both bounds.
789                        for bound in bounds {
790                            if !o.get().contains(&bound) {
791                                o.get_mut().push(bound);
792                            }
793                        }
794                    }
795                }
796            }
797            WherePredicate::ProjectionPredicate { lhs, rhs } => {
798                eq_predicates.push(WherePredicate::ProjectionPredicate { lhs, rhs });
799            }
800        }
801    }
802
803    let mut params = ThinVec::with_capacity(gens.params.len());
804    // In this loop, we gather the generic parameters (`<'a, B: 'a>`) and check if they have
805    // bounds in the where predicates. If so, we move their bounds into the where predicates
806    // while also preventing duplicates.
807    for p in gens.params.iter().filter(|p| !is_impl_trait(p) && !is_elided_lifetime(p)) {
808        let mut p = clean_generic_param(cx, Some(gens), p);
809        match &mut p.kind {
810            GenericParamDefKind::Lifetime { outlives } => {
811                if let Some(region_pred) = region_predicates.get_mut(&Lifetime(p.name)) {
812                    // We merge bounds in the `where` clause.
813                    for outlive in outlives.drain(..) {
814                        let outlive = GenericBound::Outlives(outlive);
815                        if !region_pred.contains(&outlive) {
816                            region_pred.push(outlive);
817                        }
818                    }
819                }
820            }
821            GenericParamDefKind::Type { bounds, synthetic: false, .. } => {
822                if let Some(bound_pred) = bound_predicates.get_mut(&Type::Generic(p.name)) {
823                    // We merge bounds in the `where` clause.
824                    for bound in bounds.drain(..) {
825                        if !bound_pred.0.contains(&bound) {
826                            bound_pred.0.push(bound);
827                        }
828                    }
829                }
830            }
831            GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => {
832                // nothing to do here.
833            }
834        }
835        params.push(p);
836    }
837    params.extend(impl_trait_params);
838
839    Generics {
840        params,
841        where_predicates: bound_predicates
842            .into_iter()
843            .map(|(ty, (bounds, bound_params))| WherePredicate::BoundPredicate {
844                ty,
845                bounds,
846                bound_params,
847            })
848            .chain(
849                region_predicates
850                    .into_iter()
851                    .map(|(lifetime, bounds)| WherePredicate::RegionPredicate { lifetime, bounds }),
852            )
853            .chain(eq_predicates)
854            .collect(),
855    }
856}
857
858fn clean_ty_generics<'tcx>(cx: &mut DocContext<'tcx>, def_id: DefId) -> Generics {
859    clean_ty_generics_inner(cx, cx.tcx.generics_of(def_id), cx.tcx.explicit_clauses_of(def_id))
860}
861
862fn clean_ty_generics_inner<'tcx>(
863    cx: &mut DocContext<'tcx>,
864    gens: &ty::Generics,
865    gen_clauses: ty::GenericClauses<'tcx>,
866) -> Generics {
867    // Don't populate `cx.impl_trait_bounds` before cleaning where clauses,
868    // since `clean_predicate` would consume them.
869    let mut impl_trait = BTreeMap::<u32, Vec<GenericBound>>::default();
870
871    let params: ThinVec<_> = gens
872        .own_params
873        .iter()
874        .filter(|param| match param.kind {
875            ty::GenericParamDefKind::Lifetime => !param.is_anonymous_lifetime(),
876            ty::GenericParamDefKind::Type { synthetic, .. } => {
877                if param.name == kw::SelfUpper {
878                    debug_assert_eq!(param.index, 0);
879                    return false;
880                }
881                if synthetic {
882                    impl_trait.insert(param.index, vec![]);
883                    return false;
884                }
885                true
886            }
887            ty::GenericParamDefKind::Const { .. } => true,
888        })
889        .map(|param| clean_generic_param_def(param, ParamDefaults::Yes, cx))
890        .collect();
891
892    // param index -> [(trait DefId, associated type name & generics, term)]
893    let mut impl_trait_proj =
894        FxHashMap::<u32, Vec<(DefId, PathSegment, ty::Binder<'_, ty::Term<'_>>)>>::default();
895
896    let where_clauses = gen_clauses
897        .clauses
898        .iter()
899        .flat_map(|(clause, _)| {
900            let mut proj_pred = None;
901            let param_idx = {
902                let bound_c = clause.kind();
903                match bound_c.skip_binder() {
904                    ty::ClauseKind::Trait(pred) if let ty::Param(param) = pred.self_ty().kind() => {
905                        Some(param.index)
906                    }
907                    ty::ClauseKind::TypeOutlives(ty::OutlivesClause(ty, _reg))
908                        if let ty::Param(param) = ty.kind() =>
909                    {
910                        Some(param.index)
911                    }
912                    ty::ClauseKind::Projection(p)
913                        if let ty::Param(param) = p.projection_term.self_ty().kind() =>
914                    {
915                        proj_pred = Some(bound_c.rebind(p));
916                        Some(param.index)
917                    }
918                    _ => None,
919                }
920            };
921
922            if let Some(param_idx) = param_idx
923                && let Some(bounds) = impl_trait.get_mut(&param_idx)
924            {
925                let clause = clean_clause(*clause, cx)?;
926
927                bounds.extend(clause.get_bounds().into_iter().flatten().cloned());
928
929                if let Some(pred) = proj_pred {
930                    let lhs = clean_projection(pred.map_bound(|p| p.projection_term), cx, None);
931                    impl_trait_proj.entry(param_idx).or_default().push((
932                        lhs.trait_.unwrap().def_id(),
933                        lhs.assoc,
934                        pred.map_bound(|p| p.term),
935                    ));
936                }
937
938                return None;
939            }
940
941            Some(clause)
942        })
943        .collect::<Vec<_>>();
944
945    for (idx, mut bounds) in impl_trait {
946        let mut has_sized = false;
947        bounds.retain(|b| {
948            if b.is_sized_bound(cx.tcx) {
949                has_sized = true;
950                false
951            } else if b.is_meta_sized_bound(cx.tcx) {
952                // FIXME(sized-hierarchy): Always skip `MetaSized` bounds so that only `?Sized`
953                // is shown and none of the new sizedness traits leak into documentation.
954                false
955            } else {
956                true
957            }
958        });
959        if !has_sized {
960            bounds.push(GenericBound::maybe_sized(cx));
961        }
962
963        // Move trait bounds to the front.
964        bounds.sort_by_key(|b| !b.is_trait_bound());
965
966        // Add back a `Sized` bound if there are no *trait* bounds remaining (incl. `?Sized`).
967        // Since all potential trait bounds are at the front we can just check the first bound.
968        if bounds.first().is_none_or(|b| !b.is_trait_bound()) {
969            bounds.insert(0, GenericBound::sized(cx));
970        }
971
972        if let Some(proj) = impl_trait_proj.remove(&idx) {
973            for (trait_did, name, rhs) in proj {
974                let rhs = clean_middle_term(rhs, cx);
975                simplify::merge_bounds(cx.tcx, &mut bounds, trait_did, name, &rhs);
976            }
977        }
978
979        cx.impl_trait_bounds.insert(idx.into(), bounds);
980    }
981
982    // Now that `cx.impl_trait_bounds` is populated, we can process
983    // remaining predicates which could contain `impl Trait`.
984    let where_predicates = where_clauses.into_iter().flat_map(|c| clean_clause(*c, cx)).collect();
985
986    let mut generics = Generics { params, where_predicates };
987    simplify::sizedness_bounds(cx, &mut generics);
988    generics.where_predicates = simplify::where_clauses(cx.tcx, generics.where_predicates);
989    generics
990}
991
992fn clean_ty_alias_inner_type<'tcx>(
993    ty: Ty<'tcx>,
994    cx: &mut DocContext<'tcx>,
995    ret: &mut Vec<Item>,
996) -> Option<TypeAliasInnerType> {
997    let ty::Adt(adt_def, args) = ty.kind() else {
998        return None;
999    };
1000
1001    if !adt_def.did().is_local() {
1002        cx.with_param_env(adt_def.did(), |cx| {
1003            inline::build_impls(cx, adt_def.did(), None, ret);
1004        });
1005    }
1006
1007    Some(if adt_def.is_enum() {
1008        let variants: rustc_index::IndexVec<_, _> = adt_def
1009            .variants()
1010            .iter()
1011            .map(|variant| clean_variant_def_with_args(variant, args, cx))
1012            .collect();
1013
1014        if !adt_def.did().is_local() {
1015            inline::record_extern_fqn(cx, adt_def.did(), ItemType::Enum);
1016        }
1017
1018        TypeAliasInnerType::Enum {
1019            variants,
1020            is_non_exhaustive: adt_def.is_variant_list_non_exhaustive(),
1021        }
1022    } else {
1023        let variant = adt_def
1024            .variants()
1025            .iter()
1026            .next()
1027            .unwrap_or_else(|| bug!("a struct or union should always have one variant def"));
1028
1029        let fields: Vec<_> =
1030            clean_variant_def_with_args(variant, args, cx).kind.inner_items().cloned().collect();
1031
1032        if adt_def.is_struct() {
1033            if !adt_def.did().is_local() {
1034                inline::record_extern_fqn(cx, adt_def.did(), ItemType::Struct);
1035            }
1036            TypeAliasInnerType::Struct { ctor_kind: variant.ctor_kind(), fields }
1037        } else {
1038            if !adt_def.did().is_local() {
1039                inline::record_extern_fqn(cx, adt_def.did(), ItemType::Union);
1040            }
1041            TypeAliasInnerType::Union { fields }
1042        }
1043    })
1044}
1045
1046fn clean_proc_macro<'tcx>(
1047    item: &hir::Item<'tcx>,
1048    name: &mut Symbol,
1049    kind: MacroKind,
1050    tcx: TyCtxt<'tcx>,
1051) -> ItemKind {
1052    if kind != MacroKind::Derive {
1053        return ProcMacroItem(ProcMacro { kind, helpers: vec![] });
1054    }
1055    let attrs = tcx.hir_attrs(item.hir_id());
1056    let Some((trait_name, helper_attrs)) = find_attr!(attrs, ProcMacroDerive { trait_name, helper_attrs, ..} => (*trait_name, helper_attrs))
1057    else {
1058        return ProcMacroItem(ProcMacro { kind, helpers: vec![] });
1059    };
1060    *name = trait_name;
1061    let helpers = helper_attrs.iter().copied().collect();
1062
1063    ProcMacroItem(ProcMacro { kind, helpers })
1064}
1065
1066fn clean_fn_or_proc_macro<'tcx>(
1067    item: &hir::Item<'tcx>,
1068    sig: &hir::FnSig<'tcx>,
1069    generics: &hir::Generics<'tcx>,
1070    body_id: hir::BodyId,
1071    name: &mut Symbol,
1072    cx: &mut DocContext<'tcx>,
1073) -> ItemKind {
1074    let attrs = cx.tcx.hir_attrs(item.hir_id());
1075    let macro_kind = if find_attr!(attrs, ProcMacro) {
1076        Some(MacroKind::Bang)
1077    } else if find_attr!(attrs, ProcMacroDerive { .. }) {
1078        Some(MacroKind::Derive)
1079    } else if find_attr!(attrs, ProcMacroAttribute) {
1080        Some(MacroKind::Attr)
1081    } else {
1082        None
1083    };
1084
1085    match macro_kind {
1086        Some(kind) => clean_proc_macro(item, name, kind, cx.tcx),
1087        None => {
1088            let mut func = clean_function(
1089                cx,
1090                sig,
1091                generics,
1092                ParamsSrc::Body(body_id),
1093                item.owner_id.to_def_id(),
1094            );
1095            clean_fn_decl_legacy_const_generics(&mut func, attrs);
1096            FunctionItem(func)
1097        }
1098    }
1099}
1100
1101/// This is needed to make it more "readable" when documenting functions using
1102/// `rustc_legacy_const_generics`. More information in
1103/// <https://github.com/rust-lang/rust/issues/83167>.
1104fn clean_fn_decl_legacy_const_generics(func: &mut Function, attrs: &[hir::Attribute]) {
1105    let Some(indexes) = find_attr!(attrs, RustcLegacyConstGenerics{fn_indexes,..} => fn_indexes)
1106    else {
1107        return;
1108    };
1109
1110    for (pos, (index, _)) in indexes.iter().enumerate() {
1111        let GenericParamDef { name, kind, .. } = func.generics.params.remove(0);
1112        if let GenericParamDefKind::Const { ty, .. } = kind {
1113            func.decl.inputs.insert(
1114                *index,
1115                Parameter { name: Some(name), type_: *ty, is_const: true, is_splat: false },
1116            );
1117        } else {
1118            panic!("unexpected non const in position {pos}");
1119        }
1120    }
1121}
1122
1123enum ParamsSrc<'tcx> {
1124    Body(hir::BodyId),
1125    Idents(&'tcx [Option<Ident>]),
1126}
1127
1128fn clean_function<'tcx>(
1129    cx: &mut DocContext<'tcx>,
1130    sig: &hir::FnSig<'tcx>,
1131    generics: &hir::Generics<'tcx>,
1132    params: ParamsSrc<'tcx>,
1133    def_id: DefId,
1134) -> Box<Function> {
1135    let (generics, decl) = enter_impl_trait(cx, |cx| {
1136        // NOTE: Generics must be cleaned before params.
1137        let generics = clean_generics(generics, cx);
1138        let decl = if sig.decl.opt_delegation_sig_id().is_some() {
1139            // A delegation item (`reuse path::method`) has no resolved signature in the
1140            // HIR: its inputs and return type are `InferDelegation` nodes that clean to
1141            // `_`, and an `async` header over that inferred return type would panic in
1142            // `sugared_async_return_type`. The resolved signature only exists on the ty
1143            // side, so clean that instead, exactly like an inlined item. This both fixes
1144            // the rendered `-> _` / `self: _` and makes the async sugaring well-defined.
1145            let sig = cx.tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
1146            clean_poly_fn_sig(cx, Some(def_id), sig)
1147        } else {
1148            let params = match params {
1149                ParamsSrc::Body(body_id) => clean_params_via_body(cx, sig.decl, body_id),
1150                // Let's not perpetuate anon params from Rust 2015; use `_` for them.
1151                ParamsSrc::Idents(idents) => clean_params(cx, sig.decl, idents, |ident| {
1152                    Some(ident.map_or(kw::Underscore, |ident| ident.name))
1153                }),
1154            };
1155            clean_fn_decl_with_params(cx, sig.decl, Some(&sig.header), params)
1156        };
1157        (generics, decl)
1158    });
1159    Box::new(Function { decl, generics })
1160}
1161
1162fn clean_params<'tcx>(
1163    cx: &mut DocContext<'tcx>,
1164    decl: &hir::FnDecl<'tcx>,
1165    idents: &[Option<Ident>],
1166    postprocess: impl Fn(Option<Ident>) -> Option<Symbol>,
1167) -> Vec<Parameter> {
1168    decl.inputs
1169        .iter()
1170        .enumerate()
1171        .map(|(i, ty)| Parameter {
1172            name: postprocess(idents[i]),
1173            type_: clean_ty(ty, cx),
1174            is_const: false,
1175            is_splat: decl.splatted().is_some_and(|j| j as usize == i),
1176        })
1177        .collect()
1178}
1179
1180fn clean_params_via_body<'tcx>(
1181    cx: &mut DocContext<'tcx>,
1182    decl: &hir::FnDecl<'tcx>,
1183    body_id: hir::BodyId,
1184) -> Vec<Parameter> {
1185    decl.inputs
1186        .iter()
1187        .zip(cx.tcx.hir_body(body_id).params)
1188        .enumerate()
1189        .map(|(i, (ty, param))| Parameter {
1190            name: Some(name_from_pat(param.pat)),
1191            type_: clean_ty(ty, cx),
1192            is_const: false,
1193            is_splat: decl.splatted().is_some_and(|j| j as usize == i),
1194        })
1195        .collect()
1196}
1197
1198fn clean_fn_decl_with_params<'tcx>(
1199    cx: &mut DocContext<'tcx>,
1200    decl: &hir::FnDecl<'tcx>,
1201    header: Option<&hir::FnHeader>,
1202    params: Vec<Parameter>,
1203) -> FnDecl {
1204    let mut output = match decl.output {
1205        hir::FnRetTy::Return(typ) => clean_ty(typ, cx),
1206        hir::FnRetTy::DefaultReturn(..) => Type::Tuple(Vec::new()),
1207    };
1208    if let Some(header) = header
1209        && header.is_async()
1210    {
1211        output = output.sugared_async_return_type();
1212    }
1213    FnDecl { inputs: params, output, c_variadic: decl.c_variadic() }
1214}
1215
1216fn clean_poly_fn_sig<'tcx>(
1217    cx: &mut DocContext<'tcx>,
1218    did: Option<DefId>,
1219    sig: ty::PolyFnSig<'tcx>,
1220) -> FnDecl {
1221    let mut output = clean_middle_ty(sig.output(), cx, None, None);
1222
1223    // If the return type isn't an `impl Trait`, we can safely assume that this
1224    // function isn't async without needing to execute the query `asyncness` at
1225    // all which gives us a noticeable performance boost.
1226    if let Some(did) = did
1227        && let Type::ImplTrait(_) = output
1228        && cx.tcx.asyncness(did).is_async()
1229    {
1230        output = output.sugared_async_return_type();
1231    }
1232
1233    let mut idents = did.map(|did| cx.tcx.fn_arg_idents(did)).unwrap_or_default().iter().copied();
1234
1235    // If this comes from a fn item, let's not perpetuate anon params from Rust 2015; use `_` for them.
1236    // If this comes from a fn ptr ty, we just keep params unnamed since it's more conventional stylistically.
1237    // Since the param name is not part of the semantic type, these params never bear a name unlike
1238    // in the HIR case, thus we can't perform any fancy fallback logic unlike `clean_bare_fn_ty`.
1239    let fallback = did.map(|_| kw::Underscore);
1240
1241    let params = sig
1242        .inputs()
1243        .iter()
1244        .enumerate()
1245        .map(|(i, ty)| Parameter {
1246            name: idents.next().flatten().map(|ident| ident.name).or(fallback),
1247            type_: clean_middle_ty(ty.map_bound(|ty| *ty), cx, None, None),
1248            is_const: false,
1249            is_splat: sig.splatted().is_some_and(|j| j as usize == i),
1250        })
1251        .collect();
1252
1253    FnDecl { inputs: params, output, c_variadic: sig.skip_binder().c_variadic() }
1254}
1255
1256fn clean_trait_ref<'tcx>(trait_ref: &hir::TraitRef<'tcx>, cx: &mut DocContext<'tcx>) -> Path {
1257    let path = clean_path(trait_ref.path, cx);
1258    register_res(cx, path.res);
1259    path
1260}
1261
1262fn clean_poly_trait_ref<'tcx>(
1263    poly_trait_ref: &hir::PolyTraitRef<'tcx>,
1264    cx: &mut DocContext<'tcx>,
1265) -> PolyTrait {
1266    PolyTrait {
1267        trait_: clean_trait_ref(&poly_trait_ref.trait_ref, cx),
1268        generic_params: poly_trait_ref
1269            .bound_generic_params
1270            .iter()
1271            .filter(|p| !is_elided_lifetime(p))
1272            .map(|x| clean_generic_param(cx, None, x))
1273            .collect(),
1274    }
1275}
1276
1277fn clean_trait_item<'tcx>(trait_item: &hir::TraitItem<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
1278    let local_did = trait_item.owner_id.to_def_id();
1279    cx.with_param_env(local_did, |cx| {
1280        let inner = match trait_item.kind {
1281            hir::TraitItemKind::Const(ty, Some(default)) => {
1282                ProvidedAssocConstItem(Box::new(Constant {
1283                    generics: enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx)),
1284                    kind: clean_const_item_rhs(default, local_did),
1285                    type_: clean_ty(ty, cx),
1286                }))
1287            }
1288            hir::TraitItemKind::Const(ty, None) => {
1289                let generics = enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx));
1290                RequiredAssocConstItem(generics, Box::new(clean_ty(ty, cx)))
1291            }
1292            hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
1293                let m =
1294                    clean_function(cx, sig, trait_item.generics, ParamsSrc::Body(body), local_did);
1295                MethodItem(m, Defaultness::from_trait_item(trait_item.defaultness))
1296            }
1297            hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(idents)) => {
1298                let m = clean_function(
1299                    cx,
1300                    sig,
1301                    trait_item.generics,
1302                    ParamsSrc::Idents(idents),
1303                    local_did,
1304                );
1305                RequiredMethodItem(m, Defaultness::from_trait_item(trait_item.defaultness))
1306            }
1307            hir::TraitItemKind::Type(bounds, Some(default)) => {
1308                let generics = enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx));
1309                let bounds = bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect();
1310                let item_type =
1311                    clean_middle_ty(ty::Binder::dummy(lower_ty(cx.tcx, default)), cx, None, None);
1312                AssocTypeItem(
1313                    Box::new(TypeAlias {
1314                        type_: clean_ty(default, cx),
1315                        generics,
1316                        inner_type: None,
1317                        item_type: Some(item_type),
1318                    }),
1319                    bounds,
1320                )
1321            }
1322            hir::TraitItemKind::Type(bounds, None) => {
1323                let generics = enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx));
1324                let bounds = bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect();
1325                RequiredAssocTypeItem(generics, bounds)
1326            }
1327        };
1328        Item::from_def_id_and_parts(local_did, Some(trait_item.ident.name), inner, cx.tcx)
1329    })
1330}
1331
1332pub(crate) fn clean_impl_item<'tcx>(
1333    impl_: &hir::ImplItem<'tcx>,
1334    cx: &mut DocContext<'tcx>,
1335) -> Item {
1336    let local_did = impl_.owner_id.to_def_id();
1337    cx.with_param_env(local_did, |cx| {
1338        let inner = match impl_.kind {
1339            hir::ImplItemKind::Const(ty, expr) => ImplAssocConstItem(Box::new(Constant {
1340                generics: clean_generics(impl_.generics, cx),
1341                kind: clean_const_item_rhs(expr, local_did),
1342                type_: clean_ty(ty, cx),
1343            })),
1344            hir::ImplItemKind::Fn(ref sig, body) => {
1345                let m = clean_function(cx, sig, impl_.generics, ParamsSrc::Body(body), local_did);
1346                let defaultness = match impl_.impl_kind {
1347                    hir::ImplItemImplKind::Inherent { .. } => hir::Defaultness::Final,
1348                    hir::ImplItemImplKind::Trait { defaultness, .. } => defaultness,
1349                };
1350                MethodItem(m, Defaultness::from_impl_item(defaultness))
1351            }
1352            hir::ImplItemKind::Type(hir_ty) => {
1353                let type_ = clean_ty(hir_ty, cx);
1354                let generics = clean_generics(impl_.generics, cx);
1355                let item_type =
1356                    clean_middle_ty(ty::Binder::dummy(lower_ty(cx.tcx, hir_ty)), cx, None, None);
1357                AssocTypeItem(
1358                    Box::new(TypeAlias {
1359                        type_,
1360                        generics,
1361                        inner_type: None,
1362                        item_type: Some(item_type),
1363                    }),
1364                    Vec::new(),
1365                )
1366            }
1367        };
1368
1369        Item::from_def_id_and_parts(local_did, Some(impl_.ident.name), inner, cx.tcx)
1370    })
1371}
1372
1373pub(crate) fn clean_middle_assoc_item(assoc_item: &ty::AssocItem, cx: &mut DocContext<'_>) -> Item {
1374    let tcx = cx.tcx;
1375    let kind = match assoc_item.kind {
1376        ty::AssocKind::Const { .. } => {
1377            let ty = clean_middle_ty(
1378                ty::Binder::dummy(
1379                    tcx.type_of(assoc_item.def_id).instantiate_identity().skip_norm_wip(),
1380                ),
1381                cx,
1382                Some(assoc_item.def_id),
1383                None,
1384            );
1385
1386            let mut generics = clean_ty_generics(cx, assoc_item.def_id);
1387            simplify::move_bounds_to_generic_parameters(&mut generics);
1388
1389            match assoc_item.container {
1390                ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
1391                    ImplAssocConstItem(Box::new(Constant {
1392                        generics,
1393                        kind: ConstantKind::Extern { def_id: assoc_item.def_id },
1394                        type_: ty,
1395                    }))
1396                }
1397                ty::AssocContainer::Trait => {
1398                    if tcx.defaultness(assoc_item.def_id).has_value() {
1399                        ProvidedAssocConstItem(Box::new(Constant {
1400                            generics,
1401                            kind: ConstantKind::Extern { def_id: assoc_item.def_id },
1402                            type_: ty,
1403                        }))
1404                    } else {
1405                        RequiredAssocConstItem(generics, Box::new(ty))
1406                    }
1407                }
1408            }
1409        }
1410        ty::AssocKind::Fn { has_self, .. } => {
1411            let mut item = inline::build_function(cx, assoc_item.def_id);
1412
1413            if has_self {
1414                let self_ty = match assoc_item.container {
1415                    ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => tcx
1416                        .type_of(assoc_item.container_id(tcx))
1417                        .instantiate_identity()
1418                        .skip_norm_wip(),
1419                    ty::AssocContainer::Trait => tcx.types.self_param,
1420                };
1421                let self_param_ty = tcx
1422                    .fn_sig(assoc_item.def_id)
1423                    .instantiate_identity()
1424                    .skip_norm_wip()
1425                    .input(0)
1426                    .skip_binder();
1427                if self_param_ty == self_ty {
1428                    item.decl.inputs[0].type_ = SelfTy;
1429                } else if let ty::Ref(_, ty, _) = *self_param_ty.kind()
1430                    && ty == self_ty
1431                {
1432                    match item.decl.inputs[0].type_ {
1433                        BorrowedRef { ref mut type_, .. } => **type_ = SelfTy,
1434                        _ => unreachable!(),
1435                    }
1436                }
1437            }
1438
1439            let defaultness = assoc_item.defaultness(tcx);
1440            let (provided, defaultness) = match assoc_item.container {
1441                ty::AssocContainer::Trait => {
1442                    (defaultness.has_value(), Defaultness::from_trait_item(defaultness))
1443                }
1444                ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
1445                    (true, Defaultness::from_impl_item(defaultness))
1446                }
1447            };
1448
1449            if provided {
1450                MethodItem(item, defaultness)
1451            } else {
1452                RequiredMethodItem(item, defaultness)
1453            }
1454        }
1455        ty::AssocKind::Type { .. } => {
1456            let my_name = assoc_item.name();
1457
1458            fn param_eq_arg(param: &GenericParamDef, arg: &GenericArg) -> bool {
1459                match (&param.kind, arg) {
1460                    (GenericParamDefKind::Type { .. }, GenericArg::Type(Type::Generic(ty)))
1461                        if *ty == param.name =>
1462                    {
1463                        true
1464                    }
1465                    (GenericParamDefKind::Lifetime { .. }, GenericArg::Lifetime(Lifetime(lt)))
1466                        if *lt == param.name =>
1467                    {
1468                        true
1469                    }
1470                    (GenericParamDefKind::Const { .. }, GenericArg::Const(c)) => match &**c {
1471                        ConstantKind::TyConst { expr } => **expr == *param.name.as_str(),
1472                        _ => false,
1473                    },
1474                    _ => false,
1475                }
1476            }
1477
1478            let mut clauses = tcx.explicit_clauses_of(assoc_item.def_id).clauses;
1479            if let ty::AssocContainer::Trait = assoc_item.container {
1480                let bounds = tcx
1481                    .explicit_item_bounds(assoc_item.def_id)
1482                    .iter_identity_copied()
1483                    .map(Unnormalized::skip_norm_wip);
1484                clauses = tcx.arena.alloc_from_iter(bounds.chain(clauses.iter().copied()));
1485            }
1486            let mut generics = clean_ty_generics_inner(
1487                cx,
1488                tcx.generics_of(assoc_item.def_id),
1489                ty::GenericClauses { parent: None, clauses },
1490            );
1491            simplify::move_bounds_to_generic_parameters(&mut generics);
1492
1493            if let ty::AssocContainer::Trait = assoc_item.container {
1494                // Move bounds that are (likely) directly attached to the associated type
1495                // from the where-clause to the associated type.
1496                // There is no guarantee that this is what the user actually wrote but we have
1497                // no way of knowing.
1498                let mut bounds: Vec<GenericBound> = Vec::new();
1499                generics.where_predicates.retain_mut(|pred| match *pred {
1500                    WherePredicate::BoundPredicate {
1501                        ty:
1502                            QPath(QPathData {
1503                                ref assoc, ref self_type, trait_: Some(ref trait_), ..
1504                            }),
1505                        bounds: ref mut pred_bounds,
1506                        ..
1507                    } => {
1508                        if assoc.name != my_name {
1509                            return true;
1510                        }
1511                        if trait_.def_id() != assoc_item.container_id(tcx) {
1512                            return true;
1513                        }
1514                        if *self_type != SelfTy {
1515                            return true;
1516                        }
1517                        match &assoc.args {
1518                            GenericArgs::AngleBracketed { args, constraints } => {
1519                                if !constraints.is_empty()
1520                                    || generics
1521                                        .params
1522                                        .iter()
1523                                        .zip(args.iter())
1524                                        .any(|(param, arg)| !param_eq_arg(param, arg))
1525                                {
1526                                    return true;
1527                                }
1528                            }
1529                            GenericArgs::Parenthesized { .. } => {
1530                                // The only time this happens is if we're inside the rustdoc for Fn(),
1531                                // which only has one associated type, which is not a GAT, so whatever.
1532                            }
1533                            GenericArgs::ReturnTypeNotation => {
1534                                // Never move these.
1535                            }
1536                        }
1537                        bounds.extend(mem::take(pred_bounds));
1538                        false
1539                    }
1540                    _ => true,
1541                });
1542
1543                bounds.retain(|b| {
1544                    // FIXME(sized-hierarchy): Always skip `MetaSized` bounds so that only `?Sized`
1545                    // is shown and none of the new sizedness traits leak into documentation.
1546                    !b.is_meta_sized_bound(tcx)
1547                });
1548
1549                // Our Sized/?Sized bound didn't get handled when creating the generics
1550                // because we didn't actually get our whole set of bounds until just now
1551                // (some of them may have come from the trait). If we do have a sized
1552                // bound, we remove it, and if we don't then we add the `?Sized` bound
1553                // at the end.
1554                match bounds.iter().position(|b| b.is_sized_bound(tcx)) {
1555                    Some(i) => {
1556                        bounds.remove(i);
1557                    }
1558                    None => bounds.push(GenericBound::maybe_sized(cx)),
1559                }
1560
1561                if tcx.defaultness(assoc_item.def_id).has_value() {
1562                    AssocTypeItem(
1563                        Box::new(TypeAlias {
1564                            type_: clean_middle_ty(
1565                                ty::Binder::dummy(
1566                                    tcx.type_of(assoc_item.def_id)
1567                                        .instantiate_identity()
1568                                        .skip_norm_wip(),
1569                                ),
1570                                cx,
1571                                Some(assoc_item.def_id),
1572                                None,
1573                            ),
1574                            generics,
1575                            inner_type: None,
1576                            item_type: None,
1577                        }),
1578                        bounds,
1579                    )
1580                } else {
1581                    RequiredAssocTypeItem(generics, bounds)
1582                }
1583            } else {
1584                AssocTypeItem(
1585                    Box::new(TypeAlias {
1586                        type_: clean_middle_ty(
1587                            ty::Binder::dummy(
1588                                tcx.type_of(assoc_item.def_id)
1589                                    .instantiate_identity()
1590                                    .skip_norm_wip(),
1591                            ),
1592                            cx,
1593                            Some(assoc_item.def_id),
1594                            None,
1595                        ),
1596                        generics,
1597                        inner_type: None,
1598                        item_type: None,
1599                    }),
1600                    // Associated types inside trait or inherent impls are not allowed to have
1601                    // item bounds. Thus we don't attempt to move any bounds there.
1602                    Vec::new(),
1603                )
1604            }
1605        }
1606    };
1607
1608    Item::from_def_id_and_parts(assoc_item.def_id, Some(assoc_item.name()), kind, tcx)
1609}
1610
1611fn first_non_private_clean_path<'tcx>(
1612    cx: &mut DocContext<'tcx>,
1613    path: &hir::Path<'tcx>,
1614    new_path_segments: &'tcx [hir::PathSegment<'tcx>],
1615    new_path_span: rustc_span::Span,
1616) -> Path {
1617    let new_hir_path =
1618        hir::Path { segments: new_path_segments, res: path.res, span: new_path_span };
1619    let mut new_clean_path = clean_path(&new_hir_path, cx);
1620    // In here we need to play with the path data one last time to provide it the
1621    // missing `args` and `res` of the final `Path` we get, which, since it comes
1622    // from a re-export, doesn't have the generics that were originally there, so
1623    // we add them by hand.
1624    if let Some(path_last) = path.segments.last().as_ref()
1625        && let Some(new_path_last) = new_clean_path.segments[..].last_mut()
1626        && let Some(path_last_args) = path_last.args.as_ref()
1627        && path_last.args.is_some()
1628    {
1629        assert!(new_path_last.args.is_empty());
1630        new_path_last.args = clean_generic_args(None, path_last_args, cx);
1631    }
1632    new_clean_path
1633}
1634
1635/// The goal of this function is to return the first `Path` which is not private (ie not private
1636/// or `doc(hidden)`). If it's not possible, it'll return the "end type".
1637///
1638/// If the path is not a re-export or is public, it'll return `None`.
1639fn first_non_private<'tcx>(
1640    cx: &mut DocContext<'tcx>,
1641    hir_id: hir::HirId,
1642    path: &hir::Path<'tcx>,
1643) -> Option<Path> {
1644    let target_def_id = path.res.opt_def_id()?;
1645    let (parent_def_id, ident) = match &path.segments {
1646        [] => return None,
1647        // Relative paths are available in the same scope as the owner.
1648        [leaf] => (cx.tcx.local_parent(hir_id.owner.def_id), leaf.ident),
1649        // So are self paths.
1650        [parent, leaf] if parent.ident.name == kw::SelfLower => {
1651            (cx.tcx.local_parent(hir_id.owner.def_id), leaf.ident)
1652        }
1653        // Crate paths are not. We start from the crate root.
1654        [parent, leaf] if matches!(parent.ident.name, kw::Crate | kw::PathRoot) => {
1655            (LOCAL_CRATE.as_def_id().as_local()?, leaf.ident)
1656        }
1657        [parent, leaf] if parent.ident.name == kw::Super => {
1658            let parent_mod = cx.tcx.parent_module(hir_id);
1659            if let Some(super_parent) = cx.tcx.opt_local_parent(parent_mod.to_local_def_id()) {
1660                (super_parent, leaf.ident)
1661            } else {
1662                // If we can't find the parent of the parent, then the parent is already the crate.
1663                (LOCAL_CRATE.as_def_id().as_local()?, leaf.ident)
1664            }
1665        }
1666        // Absolute paths are not. We start from the parent of the item.
1667        [.., parent, leaf] => (parent.res.opt_def_id()?.as_local()?, leaf.ident),
1668    };
1669    // First we try to get the `DefId` of the item.
1670    for child in
1671        cx.tcx.module_children_local(parent_def_id).iter().filter(move |c| c.ident == ident)
1672    {
1673        if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = child.res {
1674            continue;
1675        }
1676
1677        if let Some(def_id) = child.res.opt_def_id()
1678            && target_def_id == def_id
1679        {
1680            let mut last_path_res = None;
1681            'reexps: for reexp in child.reexport_chain.iter() {
1682                if let Some(use_def_id) = reexp.id()
1683                    && let Some(local_use_def_id) = use_def_id.as_local()
1684                    && let hir::Node::Item(item) = cx.tcx.hir_node_by_def_id(local_use_def_id)
1685                    && let hir::ItemKind::Use(path, hir::UseKind::Single(_)) = item.kind
1686                {
1687                    for res in path.res.present_items() {
1688                        if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = res {
1689                            continue;
1690                        }
1691                        if (cx.document_hidden() ||
1692                            !cx.tcx.is_doc_hidden(use_def_id)) &&
1693                            // We never check for "cx.document_private()"
1694                            // because if a re-export is not fully public, it's never
1695                            // documented.
1696                            cx.tcx.local_visibility(local_use_def_id).is_public()
1697                        {
1698                            break 'reexps;
1699                        }
1700                        last_path_res = Some((path, res));
1701                        continue 'reexps;
1702                    }
1703                }
1704            }
1705            if !child.reexport_chain.is_empty() {
1706                // So in here, we use the data we gathered from iterating the reexports. If
1707                // `last_path_res` is set, it can mean two things:
1708                //
1709                // 1. We found a public reexport.
1710                // 2. We didn't find a public reexport so it's the "end type" path.
1711                if let Some((new_path, _)) = last_path_res {
1712                    return Some(first_non_private_clean_path(
1713                        cx,
1714                        path,
1715                        new_path.segments,
1716                        new_path.span,
1717                    ));
1718                }
1719                // If `last_path_res` is `None`, it can mean two things:
1720                //
1721                // 1. The re-export is public, no need to change anything, just use the path as is.
1722                // 2. Nothing was found, so let's just return the original path.
1723                return None;
1724            }
1725        }
1726    }
1727    None
1728}
1729
1730fn clean_qpath<'tcx>(hir_ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type {
1731    let hir::Ty { hir_id, span, ref kind } = *hir_ty;
1732    let hir::TyKind::Path(qpath) = kind else { unreachable!() };
1733
1734    match qpath {
1735        hir::QPath::Resolved(None, path) => {
1736            if let Res::Def(DefKind::TyParam, did) = path.res {
1737                if let Some(new_ty) = cx.args.get(&did).and_then(|p| p.as_ty()).cloned() {
1738                    return new_ty;
1739                }
1740                if let Some(bounds) = cx.impl_trait_bounds.remove(&did.into()) {
1741                    return ImplTrait(bounds);
1742                }
1743            }
1744
1745            if let Some(expanded) = maybe_expand_private_type_alias(cx, path) {
1746                expanded
1747            } else {
1748                // First we check if it's a private re-export.
1749                let path = if let Some(path) = first_non_private(cx, hir_id, path) {
1750                    path
1751                } else {
1752                    clean_path(path, cx)
1753                };
1754                resolve_type(cx, path)
1755            }
1756        }
1757        hir::QPath::Resolved(Some(qself), p) => {
1758            // Try to normalize `<X as Y>::T` to a type
1759            let ty = lower_ty(cx.tcx, hir_ty);
1760            // `hir_to_ty` can return projection types with escaping vars for GATs, e.g. `<() as Trait>::Gat<'_>`
1761            if !ty.has_escaping_bound_vars()
1762                && let Some(normalized_value) = normalize(cx, ty::Binder::dummy(ty))
1763            {
1764                return clean_middle_ty(normalized_value, cx, None, None);
1765            }
1766
1767            let trait_segments = &p.segments[..p.segments.len() - 1];
1768            let trait_def = cx.tcx.parent(p.res.def_id());
1769            let trait_ = self::Path {
1770                res: Res::Def(DefKind::Trait, trait_def),
1771                segments: trait_segments.iter().map(|x| clean_path_segment(x, cx)).collect(),
1772            };
1773            register_res(cx, trait_.res);
1774            let self_def_id = DefId::local(qself.hir_id.owner.def_id.local_def_index);
1775            let self_type = clean_ty(qself, cx);
1776            let should_fully_qualify =
1777                should_fully_qualify_path(Some(self_def_id), &trait_, &self_type);
1778            Type::QPath(Box::new(QPathData {
1779                assoc: clean_path_segment(p.segments.last().expect("segments were empty"), cx),
1780                should_fully_qualify,
1781                self_type,
1782                trait_: Some(trait_),
1783            }))
1784        }
1785        hir::QPath::TypeRelative(qself, segment) => {
1786            let ty = lower_ty(cx.tcx, hir_ty);
1787            let self_type = clean_ty(qself, cx);
1788
1789            let (trait_, should_fully_qualify) = match ty.kind() {
1790                ty::Alias(_, proj @ ty::AliasTy { kind: ty::Projection { .. }, .. }) => {
1791                    let res = Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id);
1792                    let trait_ = clean_path(&hir::Path { span, res, segments: &[] }, cx);
1793                    register_res(cx, trait_.res);
1794                    let self_def_id = res.opt_def_id();
1795                    let should_fully_qualify =
1796                        should_fully_qualify_path(self_def_id, &trait_, &self_type);
1797
1798                    (Some(trait_), should_fully_qualify)
1799                }
1800                ty::Alias(_, ty::AliasTy { kind: ty::Inherent { .. }, .. }) => (None, false),
1801                // Rustdoc handles `ty::Error`s by turning them into `Type::Infer`s.
1802                ty::Error(_) => return Type::Infer,
1803                _ => bug!("clean: expected associated type, found `{ty:?}`"),
1804            };
1805
1806            Type::QPath(Box::new(QPathData {
1807                assoc: clean_path_segment(segment, cx),
1808                should_fully_qualify,
1809                self_type,
1810                trait_,
1811            }))
1812        }
1813    }
1814}
1815
1816fn maybe_expand_private_type_alias<'tcx>(
1817    cx: &mut DocContext<'tcx>,
1818    path: &hir::Path<'tcx>,
1819) -> Option<Type> {
1820    let Res::Def(DefKind::TyAlias, def_id) = path.res else { return None };
1821    // Substitute private type aliases
1822    let def_id = def_id.as_local()?;
1823    let alias = if !cx.cache.effective_visibilities.is_exported(cx.tcx, def_id.to_def_id())
1824        && !cx.current_type_aliases.contains_key(&def_id.to_def_id())
1825    {
1826        &cx.tcx.hir_expect_item(def_id).kind
1827    } else {
1828        return None;
1829    };
1830    let hir::ItemKind::TyAlias(_, generics, ty) = alias else { return None };
1831
1832    let final_seg = &path.segments.last().expect("segments were empty");
1833    let mut args = DefIdMap::default();
1834    let generic_args = final_seg.args();
1835
1836    let mut indices: hir::GenericParamCount = Default::default();
1837    for param in generics.params.iter() {
1838        match param.kind {
1839            hir::GenericParamKind::Lifetime { .. } => {
1840                let mut j = 0;
1841                let lifetime = generic_args.args.iter().find_map(|arg| match arg {
1842                    hir::GenericArg::Lifetime(lt) => {
1843                        if indices.lifetimes == j {
1844                            return Some(lt);
1845                        }
1846                        j += 1;
1847                        None
1848                    }
1849                    _ => None,
1850                });
1851                if let Some(lt) = lifetime {
1852                    let lt = if !lt.is_anonymous() {
1853                        clean_lifetime(lt, cx)
1854                    } else {
1855                        Lifetime::elided()
1856                    };
1857                    args.insert(param.def_id.to_def_id(), GenericArg::Lifetime(lt));
1858                }
1859                indices.lifetimes += 1;
1860            }
1861            hir::GenericParamKind::Type { ref default, .. } => {
1862                let mut j = 0;
1863                let type_ = generic_args.args.iter().find_map(|arg| match arg {
1864                    hir::GenericArg::Type(ty) => {
1865                        if indices.types == j {
1866                            return Some(ty.as_unambig_ty());
1867                        }
1868                        j += 1;
1869                        None
1870                    }
1871                    _ => None,
1872                });
1873                if let Some(ty) = type_.or(*default) {
1874                    args.insert(param.def_id.to_def_id(), GenericArg::Type(clean_ty(ty, cx)));
1875                }
1876                indices.types += 1;
1877            }
1878            // FIXME(#82852): Instantiate const parameters.
1879            hir::GenericParamKind::Const { .. } => {}
1880        }
1881    }
1882
1883    Some(cx.enter_alias(args, def_id.to_def_id(), |cx| {
1884        cx.with_param_env(def_id.to_def_id(), |cx| clean_ty(ty, cx))
1885    }))
1886}
1887
1888pub(crate) fn clean_ty<'tcx>(ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type {
1889    use rustc_hir::*;
1890
1891    match ty.kind {
1892        TyKind::Never => Primitive(PrimitiveType::Never),
1893        TyKind::Ptr(ref m) => RawPointer(m.mutbl, Box::new(clean_ty(m.ty, cx))),
1894        TyKind::Ref(l, ref m) => {
1895            let lifetime = if l.is_anonymous() { None } else { Some(clean_lifetime(l, cx)) };
1896            BorrowedRef { lifetime, mutability: m.mutbl, type_: Box::new(clean_ty(m.ty, cx)) }
1897        }
1898        TyKind::Slice(ty) => Slice(Box::new(clean_ty(ty, cx))),
1899        TyKind::Pat(inner_ty, pat) => {
1900            // Local HIR pattern types should print the same way as cross-crate inlined ones,
1901            // so lower to the canonical `rustc_middle::ty::Pattern` representation first.
1902            let pat = match lower_ty(cx.tcx, ty).kind() {
1903                ty::Pat(_, pat) => format!("{pat:?}").into_boxed_str(),
1904                _ => format!("{pat:?}").into(),
1905            };
1906            Type::Pat(Box::new(clean_ty(inner_ty, cx)), pat)
1907        }
1908        TyKind::FieldOf(ty, hir::TyFieldPath { variant, field }) => {
1909            let field_str = if let Some(variant) = variant {
1910                format!("{variant}.{field}")
1911            } else {
1912                format!("{field}")
1913            };
1914            Type::FieldOf(Box::new(clean_ty(ty, cx)), field_str.into())
1915        }
1916        TyKind::Array(ty, const_arg) => {
1917            // NOTE(min_const_generics): We can't use `const_eval_poly` for constants
1918            // as we currently do not supply the parent generics to anonymous constants
1919            // but do allow `ConstKind::Param`.
1920            //
1921            // `const_eval_poly` tries to first substitute generic parameters which
1922            // results in an ICE while manually constructing the constant and using `eval`
1923            // does nothing for `ConstKind::Param`.
1924            let length = match const_arg.kind {
1925                hir::ConstArgKind::Infer(..) | hir::ConstArgKind::Error(..) => "_".to_string(),
1926                hir::ConstArgKind::Anon(hir::AnonConst { def_id, .. }) => {
1927                    let ct = lower_const_arg_for_rustdoc(cx.tcx, const_arg, cx.tcx.types.usize);
1928                    let typing_env = ty::TypingEnv::post_analysis(cx.tcx, *def_id);
1929                    let ct =
1930                        cx.tcx.normalize_erasing_regions(typing_env, Unnormalized::new_wip(ct));
1931                    print_const(cx.tcx, ct)
1932                }
1933                hir::ConstArgKind::Struct(..)
1934                | hir::ConstArgKind::Path(..)
1935                | hir::ConstArgKind::TupleCall(..)
1936                | hir::ConstArgKind::Tup(..)
1937                | hir::ConstArgKind::Array(..)
1938                | hir::ConstArgKind::Literal { .. } => {
1939                    let ct = lower_const_arg_for_rustdoc(cx.tcx, const_arg, cx.tcx.types.usize);
1940                    print_const(cx.tcx, ct)
1941                }
1942            };
1943            Array(Box::new(clean_ty(ty, cx)), length.into())
1944        }
1945        TyKind::Tup(tys) => Tuple(tys.iter().map(|ty| clean_ty(ty, cx)).collect()),
1946        TyKind::OpaqueDef(ty) => {
1947            ImplTrait(ty.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect())
1948        }
1949        TyKind::Path(_) => clean_qpath(ty, cx),
1950        TyKind::TraitObject(bounds, lifetime) => {
1951            let bounds = bounds.iter().map(|bound| clean_poly_trait_ref(bound, cx)).collect();
1952            let lifetime = if !lifetime.is_elided() {
1953                Some(clean_lifetime(lifetime.pointer(), cx))
1954            } else {
1955                None
1956            };
1957            DynTrait(bounds, lifetime)
1958        }
1959        TyKind::FnPtr(barefn) => BareFunction(Box::new(clean_bare_fn_ty(barefn, cx))),
1960        TyKind::UnsafeBinder(unsafe_binder_ty) => {
1961            UnsafeBinder(Box::new(clean_unsafe_binder_ty(unsafe_binder_ty, cx)))
1962        }
1963        TyKind::View(ty, _) => {
1964            // FIXME(scrabsha): propagate view types to `rustdoc`.
1965            clean_ty(ty, cx)
1966        }
1967        // Rustdoc handles `TyKind::Err`s by turning them into `Type::Infer`s.
1968        TyKind::Infer(())
1969        | TyKind::Err(_)
1970        | TyKind::InferDelegation(..)
1971        | TyKind::TraitAscription(_) => Infer,
1972    }
1973}
1974
1975/// Returns `None` if the type could not be normalized
1976fn normalize<'tcx>(
1977    cx: &DocContext<'tcx>,
1978    ty: ty::Binder<'tcx, Ty<'tcx>>,
1979) -> Option<ty::Binder<'tcx, Ty<'tcx>>> {
1980    // HACK: low-churn fix for #79459 while we wait for a trait normalization fix
1981    if !cx.tcx.sess.opts.unstable_opts.normalize_docs {
1982        return None;
1983    }
1984
1985    use rustc_middle::traits::ObligationCause;
1986    use rustc_trait_selection::infer::TyCtxtInferExt;
1987    use rustc_trait_selection::traits::query::normalize::QueryNormalizeExt;
1988
1989    // Try to normalize `<X as Y>::T` to a type
1990    let infcx = cx.tcx.infer_ctxt().build(TypingMode::non_body_analysis());
1991    let normalized = infcx
1992        .at(&ObligationCause::dummy(), cx.param_env)
1993        .query_normalize(ty)
1994        .map(|resolved| infcx.resolve_vars_if_possible(resolved.value));
1995    match normalized {
1996        Ok(normalized_value) => {
1997            debug!("normalized {ty:?} to {normalized_value:?}");
1998            Some(normalized_value)
1999        }
2000        Err(err) => {
2001            debug!("failed to normalize {ty:?}: {err:?}");
2002            None
2003        }
2004    }
2005}
2006
2007fn clean_trait_object_lifetime_bound<'tcx>(
2008    region: ty::Region<'tcx>,
2009    container: Option<ContainerTy<'_, 'tcx>>,
2010    preds: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
2011    tcx: TyCtxt<'tcx>,
2012) -> Option<Lifetime> {
2013    if can_elide_trait_object_lifetime_bound(region, container, preds, tcx) {
2014        return None;
2015    }
2016
2017    // Since there is a semantic difference between an implicitly elided (i.e. "defaulted") object
2018    // lifetime and an explicitly elided object lifetime (`'_`), we intentionally don't hide the
2019    // latter contrary to `clean_middle_region`.
2020    match region.kind() {
2021        ty::ReStatic => Some(Lifetime::statik()),
2022        ty::ReEarlyParam(region) => Some(Lifetime(region.name)),
2023        ty::ReBound(_, ty::BoundRegion { kind: ty::BoundRegionKind::Named(def_id), .. }) => {
2024            Some(Lifetime(tcx.item_name(def_id)))
2025        }
2026        ty::ReBound(..)
2027        | ty::ReLateParam(_)
2028        | ty::ReVar(_)
2029        | ty::RePlaceholder(_)
2030        | ty::ReErased
2031        | ty::ReError(_) => None,
2032    }
2033}
2034
2035fn can_elide_trait_object_lifetime_bound<'tcx>(
2036    region: ty::Region<'tcx>,
2037    container: Option<ContainerTy<'_, 'tcx>>,
2038    preds: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
2039    tcx: TyCtxt<'tcx>,
2040) -> bool {
2041    // Below we quote extracts from https://doc.rust-lang.org/stable/reference/lifetime-elision.html#default-trait-object-lifetimes
2042
2043    // > If the trait object is used as a type argument of a generic type then the containing type is
2044    // > first used to try to infer a bound.
2045    let default = container
2046        .map_or(ObjectLifetimeDefault::Empty, |container| container.object_lifetime_default(tcx));
2047
2048    // > If there is a unique bound from the containing type then that is the default
2049    // If there is a default object lifetime and the given region is lexically equal to it, elide it.
2050    match default {
2051        ObjectLifetimeDefault::Static => return region.kind() == ty::ReStatic,
2052        // FIXME(fmease): Don't compare lexically but respect de Bruijn indices etc. to handle shadowing correctly.
2053        ObjectLifetimeDefault::Arg(default) => {
2054            return region.get_name(tcx) == default.get_name(tcx);
2055        }
2056        // > If there is more than one bound from the containing type then an explicit bound must be specified
2057        // Due to ambiguity there is no default trait-object lifetime and thus elision is impossible.
2058        // Don't elide the lifetime.
2059        ObjectLifetimeDefault::Ambiguous => return false,
2060        // There is no meaningful bound. Further processing is needed...
2061        ObjectLifetimeDefault::Empty => {}
2062    }
2063
2064    // > If neither of those rules apply, then the bounds on the trait are used:
2065    match *object_region_bounds(tcx, preds) {
2066        // > If the trait has no lifetime bounds, then the lifetime is inferred in expressions
2067        // > and is 'static outside of expressions.
2068        // FIXME: If we are in an expression context (i.e. fn bodies and const exprs) then the default is
2069        // `'_` and not `'static`. Only if we are in a non-expression one, the default is `'static`.
2070        // Note however that at the time of this writing it should be fine to disregard this subtlety
2071        // as we neither render const exprs faithfully anyway (hiding them in some places or using `_` instead)
2072        // nor show the contents of fn bodies.
2073        [] => region.kind() == ty::ReStatic,
2074        // > If the trait is defined with a single lifetime bound then that bound is used.
2075        // > If 'static is used for any lifetime bound then 'static is used.
2076        // FIXME(fmease): Don't compare lexically but respect de Bruijn indices etc. to handle shadowing correctly.
2077        [object_region] => object_region.get_name(tcx) == region.get_name(tcx),
2078        // There are several distinct trait regions and none are `'static`.
2079        // Due to ambiguity there is no default trait-object lifetime and thus elision is impossible.
2080        // Don't elide the lifetime.
2081        _ => false,
2082    }
2083}
2084
2085#[derive(Debug)]
2086pub(crate) enum ContainerTy<'a, 'tcx> {
2087    Ref(ty::Region<'tcx>),
2088    Regular {
2089        ty: DefId,
2090        /// The arguments *have* to contain an arg for the self type if the corresponding generics
2091        /// contain a self type.
2092        args: ty::Binder<'tcx, &'a [ty::GenericArg<'tcx>]>,
2093        arg: usize,
2094    },
2095}
2096
2097impl<'tcx> ContainerTy<'_, 'tcx> {
2098    fn object_lifetime_default(self, tcx: TyCtxt<'tcx>) -> ObjectLifetimeDefault<'tcx> {
2099        match self {
2100            Self::Ref(region) => ObjectLifetimeDefault::Arg(region),
2101            Self::Regular { ty: container, args, arg: index } => {
2102                // FIXME(fmease): Since #129543 assoc tys can now also induce trait object
2103                //                lifetime defaults. Re-elide these, too!
2104
2105                let (DefKind::Struct
2106                | DefKind::Union
2107                | DefKind::Enum
2108                | DefKind::TyAlias
2109                | DefKind::Trait) = tcx.def_kind(container)
2110                else {
2111                    return ObjectLifetimeDefault::Empty;
2112                };
2113
2114                let generics = tcx.generics_of(container);
2115                debug_assert_eq!(generics.parent_count, 0);
2116
2117                let param = generics.own_params[index].def_id;
2118                let default = tcx.object_lifetime_default(param);
2119                match default {
2120                    rbv::ObjectLifetimeDefault::Param(lifetime) => {
2121                        // The index is relative to the parent generics but since we don't have any,
2122                        // we don't need to translate it.
2123                        let index = generics.param_def_id_to_index[&lifetime];
2124                        let arg = args.skip_binder()[index as usize].expect_region();
2125                        ObjectLifetimeDefault::Arg(arg)
2126                    }
2127                    rbv::ObjectLifetimeDefault::Empty => ObjectLifetimeDefault::Empty,
2128                    rbv::ObjectLifetimeDefault::Static => ObjectLifetimeDefault::Static,
2129                    rbv::ObjectLifetimeDefault::Ambiguous => ObjectLifetimeDefault::Ambiguous,
2130                }
2131            }
2132        }
2133    }
2134}
2135
2136#[derive(Debug, Clone, Copy)]
2137pub(crate) enum ObjectLifetimeDefault<'tcx> {
2138    Empty,
2139    Static,
2140    Ambiguous,
2141    Arg(ty::Region<'tcx>),
2142}
2143
2144#[instrument(level = "trace", skip(cx), ret)]
2145pub(crate) fn clean_middle_ty<'tcx>(
2146    bound_ty: ty::Binder<'tcx, Ty<'tcx>>,
2147    cx: &mut DocContext<'tcx>,
2148    parent_def_id: Option<DefId>,
2149    container: Option<ContainerTy<'_, 'tcx>>,
2150) -> Type {
2151    let bound_ty = normalize(cx, bound_ty).unwrap_or(bound_ty);
2152    match *bound_ty.skip_binder().kind() {
2153        ty::Never => Primitive(PrimitiveType::Never),
2154        ty::Bool => Primitive(PrimitiveType::Bool),
2155        ty::Char => Primitive(PrimitiveType::Char),
2156        ty::Int(int_ty) => Primitive(int_ty.into()),
2157        ty::Uint(uint_ty) => Primitive(uint_ty.into()),
2158        ty::Float(float_ty) => Primitive(float_ty.into()),
2159        ty::Str => Primitive(PrimitiveType::Str),
2160        ty::Slice(ty) => Slice(Box::new(clean_middle_ty(bound_ty.rebind(ty), cx, None, None))),
2161        ty::Pat(ty, pat) => Type::Pat(
2162            Box::new(clean_middle_ty(bound_ty.rebind(ty), cx, None, None)),
2163            format!("{pat:?}").into_boxed_str(),
2164        ),
2165        ty::Array(ty, n) => {
2166            let n = cx
2167                .tcx
2168                .try_normalize_erasing_regions(cx.typing_env(), Unnormalized::new_wip(n))
2169                .unwrap_or(n);
2170            let n = print_const(cx.tcx, n);
2171            Array(Box::new(clean_middle_ty(bound_ty.rebind(ty), cx, None, None)), n.into())
2172        }
2173        ty::RawPtr(ty, mutbl) => {
2174            RawPointer(mutbl, Box::new(clean_middle_ty(bound_ty.rebind(ty), cx, None, None)))
2175        }
2176        ty::Ref(r, ty, mutbl) => BorrowedRef {
2177            lifetime: clean_middle_region(r, cx.tcx),
2178            mutability: mutbl,
2179            type_: Box::new(clean_middle_ty(
2180                bound_ty.rebind(ty),
2181                cx,
2182                None,
2183                Some(ContainerTy::Ref(r)),
2184            )),
2185        },
2186        ty::FnDef(..) | ty::FnPtr(..) => {
2187            // FIXME: should we merge the outer and inner binders somehow?
2188            let sig = bound_ty.skip_binder().fn_sig(cx.tcx);
2189            let decl = clean_poly_fn_sig(cx, None, sig);
2190            let generic_params = clean_bound_vars(sig.bound_vars(), cx.tcx);
2191
2192            BareFunction(Box::new(BareFunctionDecl {
2193                safety: sig.safety(),
2194                generic_params,
2195                decl,
2196                abi: sig.abi(),
2197            }))
2198        }
2199        ty::UnsafeBinder(inner) => {
2200            let generic_params = clean_bound_vars(inner.bound_vars(), cx.tcx);
2201            let ty = clean_middle_ty(inner.into(), cx, None, None);
2202            UnsafeBinder(Box::new(UnsafeBinderTy { generic_params, ty }))
2203        }
2204        ty::Adt(def, args) => {
2205            let did = def.did();
2206            let kind = match def.adt_kind() {
2207                AdtKind::Struct => ItemType::Struct,
2208                AdtKind::Union => ItemType::Union,
2209                AdtKind::Enum => ItemType::Enum,
2210            };
2211            inline::record_extern_fqn(cx, did, kind);
2212            let path = clean_middle_path(cx, did, false, ThinVec::new(), bound_ty.rebind(args));
2213            Type::Path { path }
2214        }
2215        ty::Foreign(did) => {
2216            inline::record_extern_fqn(cx, did, ItemType::ForeignType);
2217            let path = clean_middle_path(
2218                cx,
2219                did,
2220                false,
2221                ThinVec::new(),
2222                ty::Binder::dummy(ty::GenericArgs::empty()),
2223            );
2224            Type::Path { path }
2225        }
2226        ty::Dynamic(obj, reg) => {
2227            // HACK: pick the first `did` as the `did` of the trait object. Someone
2228            // might want to implement "native" support for marker-trait-only
2229            // trait objects.
2230            let mut dids = obj.auto_traits();
2231            let did = obj
2232                .principal_def_id()
2233                .or_else(|| dids.next())
2234                .unwrap_or_else(|| panic!("found trait object `{bound_ty:?}` with no traits?"));
2235            let args = match obj.principal() {
2236                Some(principal) => principal.map_bound(|p| p.args),
2237                // marker traits have no args.
2238                _ => ty::Binder::dummy(ty::GenericArgs::empty()),
2239            };
2240
2241            inline::record_extern_fqn(cx, did, ItemType::Trait);
2242
2243            let lifetime = clean_trait_object_lifetime_bound(reg, container, obj, cx.tcx);
2244
2245            let mut bounds = dids
2246                .map(|did| {
2247                    let empty = ty::Binder::dummy(ty::GenericArgs::empty());
2248                    let path = clean_middle_path(cx, did, false, ThinVec::new(), empty);
2249                    inline::record_extern_fqn(cx, did, ItemType::Trait);
2250                    PolyTrait { trait_: path, generic_params: Vec::new() }
2251                })
2252                .collect::<Vec<_>>();
2253
2254            let constraints = obj
2255                .projection_bounds()
2256                .map(|pb| AssocItemConstraint {
2257                    assoc: projection_to_path_segment(
2258                        pb.map_bound(|pb| {
2259                            pb.with_self_ty(cx.tcx, cx.tcx.types.trait_object_dummy_self)
2260                                .projection_term
2261                        }),
2262                        cx,
2263                    ),
2264                    kind: AssocItemConstraintKind::Equality {
2265                        term: clean_middle_term(pb.map_bound(|pb| pb.term), cx),
2266                    },
2267                })
2268                .collect();
2269
2270            let late_bound_regions: FxIndexSet<_> = obj
2271                .iter()
2272                .flat_map(|pred| pred.bound_vars())
2273                .filter_map(|var| match var {
2274                    ty::BoundVariableKind::Region(ty::BoundRegionKind::Named(def_id)) => {
2275                        let name = cx.tcx.item_name(def_id);
2276                        if name != kw::UnderscoreLifetime {
2277                            Some(GenericParamDef::lifetime(def_id, name))
2278                        } else {
2279                            None
2280                        }
2281                    }
2282                    _ => None,
2283                })
2284                .collect();
2285            let late_bound_regions = late_bound_regions.into_iter().collect();
2286
2287            let path = clean_middle_path(cx, did, false, constraints, args);
2288            bounds.insert(0, PolyTrait { trait_: path, generic_params: late_bound_regions });
2289
2290            DynTrait(bounds, lifetime)
2291        }
2292        ty::Tuple(t) => {
2293            Tuple(t.iter().map(|t| clean_middle_ty(bound_ty.rebind(t), cx, None, None)).collect())
2294        }
2295
2296        ty::Alias(_, alias_ty @ ty::AliasTy { kind: ty::Projection { def_id }, args, .. }) => {
2297            if cx.tcx.is_impl_trait_in_trait(def_id) {
2298                clean_middle_opaque_bounds(cx, def_id, args)
2299            } else {
2300                Type::QPath(Box::new(clean_projection(
2301                    bound_ty.rebind(alias_ty.into()),
2302                    cx,
2303                    parent_def_id,
2304                )))
2305            }
2306        }
2307
2308        ty::Alias(_, alias_ty @ ty::AliasTy { kind: ty::Inherent { def_id }, .. }) => {
2309            let alias_ty = bound_ty.rebind(alias_ty);
2310            let self_type = clean_middle_ty(alias_ty.map_bound(|ty| ty.self_ty()), cx, None, None);
2311
2312            Type::QPath(Box::new(QPathData {
2313                assoc: PathSegment {
2314                    name: cx.tcx.item_name(def_id),
2315                    args: GenericArgs::AngleBracketed {
2316                        args: clean_middle_generic_args(
2317                            cx,
2318                            alias_ty.map_bound(|ty| ty.args.as_slice()),
2319                            true,
2320                            def_id,
2321                        ),
2322                        constraints: Default::default(),
2323                    },
2324                },
2325                should_fully_qualify: false,
2326                self_type,
2327                trait_: None,
2328            }))
2329        }
2330
2331        ty::Alias(_, ty::AliasTy { kind: ty::Free { def_id }, args, .. }) => {
2332            if cx.tcx.features().checked_type_aliases() {
2333                // Free type alias `data` represents the `type X` in `type X = Y`. If we need `Y`,
2334                // we need to use `type_of`.
2335                let path =
2336                    clean_middle_path(cx, def_id, false, ThinVec::new(), bound_ty.rebind(args));
2337                Type::Path { path }
2338            } else {
2339                let ty = cx.tcx.type_of(def_id).instantiate(cx.tcx, args).skip_norm_wip();
2340                clean_middle_ty(bound_ty.rebind(ty), cx, None, None)
2341            }
2342        }
2343
2344        ty::Param(ref p) => {
2345            if let Some(bounds) = cx.impl_trait_bounds.remove(&p.index.into()) {
2346                ImplTrait(bounds)
2347            } else if p.name == kw::SelfUpper {
2348                SelfTy
2349            } else {
2350                Generic(p.name)
2351            }
2352        }
2353
2354        ty::Bound(_, ref ty) => match ty.kind {
2355            ty::BoundTyKind::Param(def_id) => Generic(cx.tcx.item_name(def_id)),
2356            ty::BoundTyKind::Anon => panic!("unexpected anonymous bound type variable"),
2357        },
2358
2359        ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) => {
2360            // If it's already in the same alias, don't get an infinite loop.
2361            if cx.current_type_aliases.contains_key(&def_id) {
2362                let path =
2363                    clean_middle_path(cx, def_id, false, ThinVec::new(), bound_ty.rebind(args));
2364                Type::Path { path }
2365            } else {
2366                *cx.current_type_aliases.entry(def_id).or_insert(0) += 1;
2367                // Grab the "TraitA + TraitB" from `impl TraitA + TraitB`,
2368                // by looking up the bounds associated with the def_id.
2369                let ty = clean_middle_opaque_bounds(cx, def_id, args);
2370                if let Some(count) = cx.current_type_aliases.get_mut(&def_id) {
2371                    *count -= 1;
2372                    if *count == 0 {
2373                        cx.current_type_aliases.remove(&def_id);
2374                    }
2375                }
2376                ty
2377            }
2378        }
2379
2380        ty::Closure(..) => panic!("Closure"),
2381        ty::CoroutineClosure(..) => panic!("CoroutineClosure"),
2382        ty::Coroutine(..) => panic!("Coroutine"),
2383        ty::Placeholder(..) => panic!("Placeholder"),
2384        ty::CoroutineWitness(..) => panic!("CoroutineWitness"),
2385        ty::Infer(..) => panic!("Infer"),
2386
2387        ty::Error(_) => FatalError.raise(),
2388    }
2389}
2390
2391fn clean_middle_opaque_bounds<'tcx>(
2392    cx: &mut DocContext<'tcx>,
2393    impl_trait_def_id: DefId,
2394    args: ty::GenericArgsRef<'tcx>,
2395) -> Type {
2396    let mut has_sized = false;
2397
2398    let bounds: Vec<_> = cx
2399        .tcx
2400        .explicit_item_bounds(impl_trait_def_id)
2401        .iter_instantiated_copied(cx.tcx, args)
2402        .map(Unnormalized::skip_norm_wip)
2403        .collect();
2404
2405    let mut bounds = bounds
2406        .iter()
2407        .filter_map(|(bound, _)| {
2408            let bound_predicate = bound.kind();
2409            let trait_ref = match bound_predicate.skip_binder() {
2410                ty::ClauseKind::Trait(tr) => bound_predicate.rebind(tr.trait_ref),
2411                ty::ClauseKind::TypeOutlives(ty::OutlivesClause(_ty, reg)) => {
2412                    return clean_middle_region(reg, cx.tcx).map(GenericBound::Outlives);
2413                }
2414                _ => return None,
2415            };
2416
2417            // FIXME(sized-hierarchy): Always skip `MetaSized` bounds so that only `?Sized`
2418            // is shown and none of the new sizedness traits leak into documentation.
2419            if cx.tcx.is_lang_item(trait_ref.def_id(), LangItem::MetaSized) {
2420                return None;
2421            }
2422
2423            if let Some(sized) = cx.tcx.lang_items().sized_trait()
2424                && trait_ref.def_id() == sized
2425            {
2426                has_sized = true;
2427                return None;
2428            }
2429
2430            let bindings: ThinVec<_> = bounds
2431                .iter()
2432                .filter_map(|(bound, _)| {
2433                    let bound = bound.kind();
2434                    if let ty::ClauseKind::Projection(proj_pred) = bound.skip_binder()
2435                        && proj_pred.projection_term.trait_ref(cx.tcx) == trait_ref.skip_binder()
2436                    {
2437                        return Some(AssocItemConstraint {
2438                            assoc: projection_to_path_segment(
2439                                bound.rebind(proj_pred.projection_term),
2440                                cx,
2441                            ),
2442                            kind: AssocItemConstraintKind::Equality {
2443                                term: clean_middle_term(bound.rebind(proj_pred.term), cx),
2444                            },
2445                        });
2446                    }
2447                    None
2448                })
2449                .collect();
2450
2451            Some(clean_poly_trait_ref_with_constraints(cx, trait_ref, bindings))
2452        })
2453        .collect::<Vec<_>>();
2454
2455    if !has_sized {
2456        bounds.push(GenericBound::maybe_sized(cx));
2457    }
2458
2459    // Move trait bounds to the front.
2460    bounds.sort_by_key(|b| !b.is_trait_bound());
2461
2462    // Add back a `Sized` bound if there are no *trait* bounds remaining (incl. `?Sized`).
2463    // Since all potential trait bounds are at the front we can just check the first bound.
2464    if bounds.first().is_none_or(|b| !b.is_trait_bound()) {
2465        bounds.insert(0, GenericBound::sized(cx));
2466    }
2467
2468    if let Some(args) = cx.tcx.rendered_precise_capturing_args(impl_trait_def_id) {
2469        bounds.push(GenericBound::Use(
2470            args.iter()
2471                .map(|arg| match arg {
2472                    hir::PreciseCapturingArgKind::Lifetime(lt) => {
2473                        PreciseCapturingArg::Lifetime(Lifetime(*lt))
2474                    }
2475                    hir::PreciseCapturingArgKind::Param(param) => {
2476                        PreciseCapturingArg::Param(*param)
2477                    }
2478                })
2479                .collect(),
2480        ));
2481    }
2482
2483    ImplTrait(bounds)
2484}
2485
2486pub(crate) fn clean_field<'tcx>(field: &hir::FieldDef<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
2487    clean_field_with_def_id(
2488        field.def_id.to_def_id(),
2489        field.ident.name,
2490        clean_ty(field.ty, cx),
2491        cx.tcx,
2492    )
2493}
2494
2495pub(crate) fn clean_middle_field(field: &ty::FieldDef, cx: &mut DocContext<'_>) -> Item {
2496    clean_field_with_def_id(
2497        field.did,
2498        field.name,
2499        clean_middle_ty(
2500            ty::Binder::dummy(cx.tcx.type_of(field.did).instantiate_identity().skip_norm_wip()),
2501            cx,
2502            Some(field.did),
2503            None,
2504        ),
2505        cx.tcx,
2506    )
2507}
2508
2509pub(crate) fn clean_field_with_def_id(
2510    def_id: DefId,
2511    name: Symbol,
2512    ty: Type,
2513    tcx: TyCtxt<'_>,
2514) -> Item {
2515    Item::from_def_id_and_parts(def_id, Some(name), StructFieldItem(ty), tcx)
2516}
2517
2518pub(crate) fn clean_variant_def(variant: &ty::VariantDef, cx: &mut DocContext<'_>) -> Item {
2519    let discriminant = match variant.discr {
2520        ty::VariantDiscr::Explicit(def_id) => Some(Discriminant { expr: None, value: def_id }),
2521        ty::VariantDiscr::Relative(_) => None,
2522    };
2523
2524    let kind = match variant.ctor_kind() {
2525        Some(CtorKind::Const) => VariantKind::CLike,
2526        Some(CtorKind::Fn) => VariantKind::Tuple(
2527            variant.fields.iter().map(|field| clean_middle_field(field, cx)).collect(),
2528        ),
2529        None => VariantKind::Struct(VariantStruct {
2530            fields: variant.fields.iter().map(|field| clean_middle_field(field, cx)).collect(),
2531        }),
2532    };
2533
2534    Item::from_def_id_and_parts(
2535        variant.def_id,
2536        Some(variant.name),
2537        VariantItem(Variant { kind, discriminant }),
2538        cx.tcx,
2539    )
2540}
2541
2542pub(crate) fn clean_variant_def_with_args<'tcx>(
2543    variant: &ty::VariantDef,
2544    args: &GenericArgsRef<'tcx>,
2545    cx: &mut DocContext<'tcx>,
2546) -> Item {
2547    let discriminant = match variant.discr {
2548        ty::VariantDiscr::Explicit(def_id) => Some(Discriminant { expr: None, value: def_id }),
2549        ty::VariantDiscr::Relative(_) => None,
2550    };
2551
2552    use rustc_middle::traits::ObligationCause;
2553    use rustc_trait_selection::infer::TyCtxtInferExt;
2554    use rustc_trait_selection::traits::query::normalize::QueryNormalizeExt;
2555
2556    let infcx = cx.tcx.infer_ctxt().build(TypingMode::non_body_analysis());
2557    let kind = match variant.ctor_kind() {
2558        Some(CtorKind::Const) => VariantKind::CLike,
2559        Some(CtorKind::Fn) => VariantKind::Tuple(
2560            variant
2561                .fields
2562                .iter()
2563                .map(|field| {
2564                    let ty = cx.tcx.type_of(field.did).instantiate(cx.tcx, args).skip_norm_wip();
2565
2566                    // normalize the type to only show concrete types
2567                    // note: we do not use try_normalize_erasing_regions since we
2568                    // do care about showing the regions
2569                    let ty = infcx
2570                        .at(&ObligationCause::dummy(), cx.param_env)
2571                        .query_normalize(ty)
2572                        .map(|normalized| normalized.value)
2573                        .unwrap_or(ty);
2574
2575                    clean_field_with_def_id(
2576                        field.did,
2577                        field.name,
2578                        clean_middle_ty(ty::Binder::dummy(ty), cx, Some(field.did), None),
2579                        cx.tcx,
2580                    )
2581                })
2582                .collect(),
2583        ),
2584        None => VariantKind::Struct(VariantStruct {
2585            fields: variant
2586                .fields
2587                .iter()
2588                .map(|field| {
2589                    let ty = cx.tcx.type_of(field.did).instantiate(cx.tcx, args).skip_norm_wip();
2590
2591                    // normalize the type to only show concrete types
2592                    // note: we do not use try_normalize_erasing_regions since we
2593                    // do care about showing the regions
2594                    let ty = infcx
2595                        .at(&ObligationCause::dummy(), cx.param_env)
2596                        .query_normalize(ty)
2597                        .map(|normalized| normalized.value)
2598                        .unwrap_or(ty);
2599
2600                    clean_field_with_def_id(
2601                        field.did,
2602                        field.name,
2603                        clean_middle_ty(ty::Binder::dummy(ty), cx, Some(field.did), None),
2604                        cx.tcx,
2605                    )
2606                })
2607                .collect(),
2608        }),
2609    };
2610
2611    Item::from_def_id_and_parts(
2612        variant.def_id,
2613        Some(variant.name),
2614        VariantItem(Variant { kind, discriminant }),
2615        cx.tcx,
2616    )
2617}
2618
2619fn clean_variant_data<'tcx>(
2620    variant: &hir::VariantData<'tcx>,
2621    disr_expr: &Option<&hir::AnonConst>,
2622    cx: &mut DocContext<'tcx>,
2623) -> Variant {
2624    let discriminant = disr_expr
2625        .map(|disr| Discriminant { expr: Some(disr.body), value: disr.def_id.to_def_id() });
2626
2627    let kind = match variant {
2628        hir::VariantData::Struct { fields, .. } => VariantKind::Struct(VariantStruct {
2629            fields: fields.iter().map(|x| clean_field(x, cx)).collect(),
2630        }),
2631        hir::VariantData::Tuple(..) => {
2632            VariantKind::Tuple(variant.fields().iter().map(|x| clean_field(x, cx)).collect())
2633        }
2634        hir::VariantData::Unit(..) => VariantKind::CLike,
2635    };
2636
2637    Variant { discriminant, kind }
2638}
2639
2640fn clean_path<'tcx>(path: &hir::Path<'tcx>, cx: &mut DocContext<'tcx>) -> Path {
2641    Path {
2642        res: path.res,
2643        segments: path.segments.iter().map(|x| clean_path_segment(x, cx)).collect(),
2644    }
2645}
2646
2647fn clean_generic_args<'tcx>(
2648    trait_did: Option<DefId>,
2649    generic_args: &hir::GenericArgs<'tcx>,
2650    cx: &mut DocContext<'tcx>,
2651) -> GenericArgs {
2652    match generic_args.parenthesized {
2653        hir::GenericArgsParentheses::No => {
2654            let args = generic_args
2655                .args
2656                .iter()
2657                .map(|arg| match arg {
2658                    hir::GenericArg::Lifetime(lt) if !lt.is_anonymous() => {
2659                        GenericArg::Lifetime(clean_lifetime(lt, cx))
2660                    }
2661                    hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
2662                    hir::GenericArg::Type(ty) => GenericArg::Type(clean_ty(ty.as_unambig_ty(), cx)),
2663                    hir::GenericArg::Const(ct) => {
2664                        GenericArg::Const(Box::new(clean_const(ct.as_unambig_ct())))
2665                    }
2666                    hir::GenericArg::Infer(_inf) => GenericArg::Infer,
2667                })
2668                .collect();
2669            let constraints = generic_args
2670                .constraints
2671                .iter()
2672                .map(|c| {
2673                    clean_assoc_item_constraint(
2674                        trait_did.expect("only trait ref has constraints"),
2675                        c,
2676                        cx,
2677                    )
2678                })
2679                .collect::<ThinVec<_>>();
2680            GenericArgs::AngleBracketed { args, constraints }
2681        }
2682        hir::GenericArgsParentheses::ParenSugar => {
2683            let Some((inputs, output)) = generic_args.paren_sugar_inputs_output() else {
2684                bug!();
2685            };
2686            let inputs = inputs.iter().map(|x| clean_ty(x, cx)).collect();
2687            let output = match output.kind {
2688                hir::TyKind::Tup(&[]) => None,
2689                _ => Some(Box::new(clean_ty(output, cx))),
2690            };
2691            GenericArgs::Parenthesized { inputs, output }
2692        }
2693        hir::GenericArgsParentheses::ReturnTypeNotation => GenericArgs::ReturnTypeNotation,
2694    }
2695}
2696
2697fn clean_path_segment<'tcx>(
2698    path: &hir::PathSegment<'tcx>,
2699    cx: &mut DocContext<'tcx>,
2700) -> PathSegment {
2701    let trait_did = match path.res {
2702        hir::def::Res::Def(DefKind::Trait | DefKind::TraitAlias, did) => Some(did),
2703        _ => None,
2704    };
2705    PathSegment { name: path.ident.name, args: clean_generic_args(trait_did, path.args(), cx) }
2706}
2707
2708fn clean_bare_fn_ty<'tcx>(
2709    bare_fn: &hir::FnPtrTy<'tcx>,
2710    cx: &mut DocContext<'tcx>,
2711) -> BareFunctionDecl {
2712    let (generic_params, decl) = enter_impl_trait(cx, |cx| {
2713        // NOTE: Generics must be cleaned before params.
2714        let generic_params = bare_fn
2715            .generic_params
2716            .iter()
2717            .filter(|p| !is_elided_lifetime(p))
2718            .map(|x| clean_generic_param(cx, None, x))
2719            .collect();
2720        // Since it's more conventional stylistically, elide the name of all params called `_`
2721        // unless there's at least one interestingly named param in which case don't elide any
2722        // name since mixing named and unnamed params is less legible.
2723        let filter = |ident: Option<Ident>| {
2724            ident.map(|ident| ident.name).filter(|&ident| ident != kw::Underscore)
2725        };
2726        let fallback =
2727            bare_fn.param_idents.iter().copied().find_map(filter).map(|_| kw::Underscore);
2728        let params = clean_params(cx, bare_fn.decl, bare_fn.param_idents, |ident| {
2729            filter(ident).or(fallback)
2730        });
2731        let decl = clean_fn_decl_with_params(cx, bare_fn.decl, None, params);
2732        (generic_params, decl)
2733    });
2734    BareFunctionDecl { safety: bare_fn.safety, abi: bare_fn.abi, decl, generic_params }
2735}
2736
2737fn clean_unsafe_binder_ty<'tcx>(
2738    unsafe_binder_ty: &hir::UnsafeBinderTy<'tcx>,
2739    cx: &mut DocContext<'tcx>,
2740) -> UnsafeBinderTy {
2741    let generic_params = unsafe_binder_ty
2742        .generic_params
2743        .iter()
2744        .filter(|p| !is_elided_lifetime(p))
2745        .map(|x| clean_generic_param(cx, None, x))
2746        .collect();
2747    let ty = clean_ty(unsafe_binder_ty.inner_ty, cx);
2748    UnsafeBinderTy { generic_params, ty }
2749}
2750
2751pub(crate) fn reexport_chain(
2752    tcx: TyCtxt<'_>,
2753    import_def_id: LocalDefId,
2754    target_def_id: DefId,
2755) -> &[Reexport] {
2756    for child in tcx.module_children_local(tcx.local_parent(import_def_id)) {
2757        if child.res.opt_def_id() == Some(target_def_id)
2758            && child.reexport_chain.first().and_then(|r| r.id()) == Some(import_def_id.to_def_id())
2759        {
2760            return &child.reexport_chain;
2761        }
2762    }
2763    &[]
2764}
2765
2766/// Collect attributes from the whole import chain.
2767fn get_all_import_attributes<'hir>(
2768    cx: &mut DocContext<'hir>,
2769    import_def_id: LocalDefId,
2770    target_def_id: DefId,
2771    is_inline: bool,
2772) -> Vec<(Cow<'hir, hir::Attribute>, Option<DefId>)> {
2773    let mut attrs = Vec::new();
2774    let mut first = true;
2775    for def_id in reexport_chain(cx.tcx, import_def_id, target_def_id)
2776        .iter()
2777        .flat_map(|reexport| reexport.id())
2778    {
2779        let import_attrs = inline::load_attrs(cx.tcx, def_id);
2780        if first {
2781            // This is the "original" reexport so we get all its attributes without filtering them.
2782            attrs = import_attrs.iter().map(|attr| (Cow::Borrowed(attr), Some(def_id))).collect();
2783            first = false;
2784        // We don't add attributes of an intermediate re-export if it has `#[doc(hidden)]`.
2785        } else if cx.document_hidden() || !cx.tcx.is_doc_hidden(def_id) {
2786            add_without_unwanted_attributes(&mut attrs, import_attrs, is_inline, Some(def_id));
2787        }
2788    }
2789    attrs
2790}
2791
2792/// When inlining items, we merge their attributes (and all the reexports attributes too) with the
2793/// final reexport. For example:
2794///
2795/// ```ignore (just an example)
2796/// #[doc(hidden, cfg(feature = "foo"))]
2797/// pub struct Foo;
2798///
2799/// #[doc(cfg(feature = "bar"))]
2800/// #[doc(hidden, no_inline)]
2801/// pub use Foo as Foo1;
2802///
2803/// #[doc(inline)]
2804/// pub use Foo2 as Bar;
2805/// ```
2806///
2807/// So `Bar` at the end will have both `cfg(feature = "...")`. However, we don't want to merge all
2808/// attributes so we filter out the following ones:
2809/// * `doc(inline)`
2810/// * `doc(no_inline)`
2811/// * `doc(hidden)`
2812fn add_without_unwanted_attributes<'hir>(
2813    attrs: &mut Vec<(Cow<'hir, hir::Attribute>, Option<DefId>)>,
2814    new_attrs: &'hir [hir::Attribute],
2815    is_inline: bool,
2816    import_parent: Option<DefId>,
2817) {
2818    for attr in new_attrs {
2819        match attr {
2820            hir::Attribute::Parsed(AttributeKind::DocComment { .. }) => {
2821                attrs.push((Cow::Borrowed(attr), import_parent));
2822            }
2823            hir::Attribute::Parsed(AttributeKind::Doc(d)) => {
2824                // Remove attributes from `normal` that should not be inherited by `use` re-export.
2825                let DocAttribute {
2826                    first_span: _,
2827                    aliases,
2828                    hidden,
2829                    inline,
2830                    cfg,
2831                    auto_cfg: _,
2832                    auto_cfg_change: _,
2833                    fake_variadic: _,
2834                    keyword: _,
2835                    attribute: _,
2836                    masked: _,
2837                    notable_trait: _,
2838                    search_unbox: _,
2839                    html_favicon_url: _,
2840                    html_logo_url: _,
2841                    html_playground_url: _,
2842                    html_root_url: _,
2843                    html_no_source: _,
2844                    issue_tracker_base_url: _,
2845                    rust_logo: _,
2846                    test_attrs: _,
2847                    no_crate_inject: _,
2848                } = d;
2849                let mut attr = DocAttribute::default();
2850                if is_inline {
2851                    attr.cfg = cfg.clone();
2852                } else {
2853                    attr.inline = inline.clone();
2854                    attr.hidden = hidden.clone();
2855                }
2856                attr.aliases = aliases.clone();
2857                attrs.push((
2858                    Cow::Owned(hir::Attribute::Parsed(AttributeKind::Doc(Box::new(attr)))),
2859                    import_parent,
2860                ));
2861            }
2862
2863            // We discard `#[cfg(...)]` attributes unless we're inlining
2864            hir::Attribute::Parsed(AttributeKind::CfgTrace(..)) if !is_inline => {}
2865            // We keep all other attributes
2866            _ => {
2867                attrs.push((Cow::Borrowed(attr), import_parent));
2868            }
2869        }
2870    }
2871}
2872
2873fn clean_maybe_renamed_item<'tcx>(
2874    cx: &mut DocContext<'tcx>,
2875    item: &hir::Item<'tcx>,
2876    renamed: Option<Symbol>,
2877    import_ids: &[LocalDefId],
2878) -> Vec<Item> {
2879    use hir::ItemKind;
2880    fn get_name(tcx: TyCtxt<'_>, item: &hir::Item<'_>, renamed: Option<Symbol>) -> Option<Symbol> {
2881        renamed.or_else(|| tcx.hir_opt_name(item.hir_id()))
2882    }
2883
2884    let def_id = item.owner_id.to_def_id();
2885    cx.with_param_env(def_id, |cx| {
2886        // These kinds of item either don't need a `name` or accept a `None` one so we handle them
2887        // before.
2888        match item.kind {
2889            ItemKind::Impl(ref impl_) => {
2890                // If `renamed` is `Some()` for an `impl`, it means it's been inlined because we use
2891                // it as a marker to indicate that this is an inlined impl and that we should
2892                // generate an impl placeholder and not a "real" impl item.
2893                return clean_impl(impl_, item.owner_id.def_id, cx, renamed.is_some());
2894            }
2895            ItemKind::Use(path, kind) => {
2896                return clean_use_statement(
2897                    item,
2898                    get_name(cx.tcx, item, renamed),
2899                    path,
2900                    kind,
2901                    cx,
2902                    &mut FxHashSet::default(),
2903                );
2904            }
2905            _ => {}
2906        }
2907
2908        let mut name = get_name(cx.tcx, item, renamed).unwrap();
2909
2910        let kind = match item.kind {
2911            ItemKind::Static(mutability, _, ty, body_id) => StaticItem(Static {
2912                type_: Box::new(clean_ty(ty, cx)),
2913                mutability,
2914                expr: Some(body_id),
2915            }),
2916            ItemKind::Const(_, generics, ty, rhs) => ConstantItem(Box::new(Constant {
2917                generics: clean_generics(generics, cx),
2918                type_: clean_ty(ty, cx),
2919                kind: clean_const_item_rhs(rhs, def_id),
2920            })),
2921            ItemKind::TyAlias(_, generics, ty) => {
2922                *cx.current_type_aliases.entry(def_id).or_insert(0) += 1;
2923                let rustdoc_ty = clean_ty(ty, cx);
2924                let type_ =
2925                    clean_middle_ty(ty::Binder::dummy(lower_ty(cx.tcx, ty)), cx, None, None);
2926                let generics = clean_generics(generics, cx);
2927                if let Some(count) = cx.current_type_aliases.get_mut(&def_id) {
2928                    *count -= 1;
2929                    if *count == 0 {
2930                        cx.current_type_aliases.remove(&def_id);
2931                    }
2932                }
2933
2934                let ty = cx.tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
2935
2936                let mut ret = Vec::new();
2937                let inner_type = clean_ty_alias_inner_type(ty, cx, &mut ret);
2938
2939                ret.push(generate_item_with_correct_attrs(
2940                    cx,
2941                    TypeAliasItem(Box::new(TypeAlias {
2942                        generics,
2943                        inner_type,
2944                        type_: rustdoc_ty,
2945                        item_type: Some(type_),
2946                    })),
2947                    item.owner_id.def_id.to_def_id(),
2948                    name,
2949                    import_ids,
2950                    renamed,
2951                ));
2952                return ret;
2953            }
2954            ItemKind::Enum(_, generics, def) => EnumItem(Enum {
2955                variants: def.variants.iter().map(|v| clean_variant(v, cx)).collect(),
2956                generics: clean_generics(generics, cx),
2957            }),
2958            ItemKind::TraitAlias(_, _, generics, bounds) => TraitAliasItem(TraitAlias {
2959                generics: clean_generics(generics, cx),
2960                bounds: bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
2961            }),
2962            ItemKind::Union(_, generics, variant_data) => UnionItem(Union {
2963                generics: clean_generics(generics, cx),
2964                fields: variant_data.fields().iter().map(|x| clean_field(x, cx)).collect(),
2965            }),
2966            ItemKind::Struct(_, generics, variant_data) => StructItem(Struct {
2967                ctor_kind: variant_data.ctor_kind(),
2968                generics: clean_generics(generics, cx),
2969                fields: variant_data.fields().iter().map(|x| clean_field(x, cx)).collect(),
2970            }),
2971            ItemKind::Macro(_, macro_def, kinds) => match kinds {
2972                MacroKinds::ATTR => clean_proc_macro(item, &mut name, MacroKind::Attr, cx.tcx),
2973                MacroKinds::DERIVE => clean_proc_macro(item, &mut name, MacroKind::Derive, cx.tcx),
2974                _ => MacroItem(
2975                    Macro {
2976                        source: display_macro_source(cx.tcx, name, macro_def),
2977                        macro_rules: macro_def.macro_rules,
2978                    },
2979                    kinds,
2980                ),
2981            },
2982            // proc macros can have a name set by attributes
2983            ItemKind::Fn { ref sig, generics, body: body_id, .. } => {
2984                clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx)
2985            }
2986            // FIXME: rustdoc will need to handle `impl` restrictions at some point
2987            ItemKind::Trait { generics, bounds, items: item_ids, .. } => {
2988                let items = item_ids
2989                    .iter()
2990                    .map(|&ti| clean_trait_item(cx.tcx.hir_trait_item(ti), cx))
2991                    .collect();
2992
2993                TraitItem(Box::new(Trait {
2994                    def_id,
2995                    items,
2996                    generics: clean_generics(generics, cx),
2997                    bounds: bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
2998                }))
2999            }
3000            ItemKind::ExternCrate(orig_name, _) => {
3001                return clean_extern_crate(item, name, orig_name, cx);
3002            }
3003            _ => span_bug!(item.span, "not yet converted"),
3004        };
3005
3006        vec![generate_item_with_correct_attrs(
3007            cx,
3008            kind,
3009            item.owner_id.def_id.to_def_id(),
3010            name,
3011            import_ids,
3012            renamed,
3013        )]
3014    })
3015}
3016
3017fn clean_variant<'tcx>(variant: &hir::Variant<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
3018    let kind = VariantItem(clean_variant_data(&variant.data, &variant.disr_expr, cx));
3019    Item::from_def_id_and_parts(variant.def_id.to_def_id(), Some(variant.ident.name), kind, cx.tcx)
3020}
3021
3022fn clean_impl<'tcx>(
3023    impl_: &hir::Impl<'tcx>,
3024    def_id: LocalDefId,
3025    cx: &mut DocContext<'tcx>,
3026    // If true, this is an inlined impl and it will be handled later on in the code.
3027    // In here, we will generate a placeholder for it in order to be able to compute its
3028    // `doc_cfg` info.
3029    is_inlined: bool,
3030) -> Vec<Item> {
3031    let tcx = cx.tcx;
3032    let mut ret = Vec::new();
3033    let trait_ = match impl_.of_trait {
3034        Some(t) => {
3035            if is_inlined {
3036                return vec![Item::from_def_id_and_parts(
3037                    def_id.to_def_id(),
3038                    None,
3039                    PlaceholderImplItem,
3040                    tcx,
3041                )];
3042            }
3043            Some(clean_trait_ref(&t.trait_ref, cx))
3044        }
3045        None => None,
3046    };
3047    let items = impl_
3048        .items
3049        .iter()
3050        .map(|&ii| clean_impl_item(tcx.hir_impl_item(ii), cx))
3051        .collect::<Vec<_>>();
3052
3053    // If this impl block is a positive implementation of the Deref trait, then we
3054    // need to try inlining the target's inherent impl blocks as well.
3055    if trait_.as_ref().is_some_and(|t| tcx.lang_items().deref_trait() == Some(t.def_id()))
3056        && tcx.impl_polarity(def_id) != ty::ImplPolarity::Negative
3057    {
3058        build_deref_target_impls(cx, &items, &mut ret);
3059    }
3060
3061    let for_ = clean_ty(impl_.self_ty, cx);
3062    let type_alias =
3063        for_.def_id(&cx.cache).and_then(|alias_def_id: DefId| match tcx.def_kind(alias_def_id) {
3064            DefKind::TyAlias => Some(clean_middle_ty(
3065                ty::Binder::dummy(tcx.type_of(def_id).instantiate_identity().skip_norm_wip()),
3066                cx,
3067                Some(def_id.to_def_id()),
3068                None,
3069            )),
3070            _ => None,
3071        });
3072    let is_deprecated = tcx
3073        .lookup_deprecation(def_id.to_def_id())
3074        .is_some_and(|deprecation| deprecation.is_in_effect());
3075    let mut make_item = |trait_: Option<Path>, for_: Type, items: Vec<Item>| {
3076        let kind = ImplItem(Box::new(Impl {
3077            safety: match impl_.of_trait {
3078                Some(of_trait) => of_trait.safety,
3079                None => hir::Safety::Safe,
3080            },
3081            generics: clean_generics(impl_.generics, cx),
3082            trait_,
3083            for_,
3084            items,
3085            polarity: if impl_.of_trait.is_some() {
3086                tcx.impl_polarity(def_id)
3087            } else {
3088                ty::ImplPolarity::Positive
3089            },
3090            kind: if utils::has_doc_flag(tcx, def_id.to_def_id(), |d| d.fake_variadic.is_some()) {
3091                ImplKind::FakeVariadic
3092            } else {
3093                ImplKind::Normal
3094            },
3095            is_deprecated,
3096        }));
3097        Item::from_def_id_and_parts(def_id.to_def_id(), None, kind, tcx)
3098    };
3099    if let Some(type_alias) = type_alias {
3100        ret.push(make_item(trait_.clone(), type_alias, items.clone()));
3101    }
3102    ret.push(make_item(trait_, for_, items));
3103    ret
3104}
3105
3106fn clean_extern_crate<'tcx>(
3107    krate: &hir::Item<'tcx>,
3108    name: Symbol,
3109    orig_name: Option<Symbol>,
3110    cx: &mut DocContext<'tcx>,
3111) -> Vec<Item> {
3112    // this is the ID of the `extern crate` statement
3113    let cnum = cx.tcx.extern_mod_stmt_cnum(krate.owner_id.def_id).unwrap_or(LOCAL_CRATE);
3114    // this is the ID of the crate itself
3115    let crate_def_id = cnum.as_def_id();
3116    let attrs = cx.tcx.hir_attrs(krate.hir_id());
3117    let ty_vis = cx.tcx.visibility(krate.owner_id);
3118    let please_inline = ty_vis.is_public()
3119        && attrs.iter().any(|a| {
3120            matches!(
3121            a,
3122            hir::Attribute::Parsed(AttributeKind::Doc(d))
3123            if d.inline.first().is_some_and(|(i, _)| *i == DocInline::Inline))
3124        })
3125        && !cx.is_json_output();
3126
3127    let krate_owner_def_id = krate.owner_id.def_id;
3128
3129    if please_inline
3130        && let Some(items) = inline::try_inline(
3131            cx,
3132            Res::Def(DefKind::Mod, crate_def_id),
3133            name,
3134            Some((attrs, Some(krate_owner_def_id))),
3135            &mut Default::default(),
3136        )
3137    {
3138        return items;
3139    }
3140
3141    vec![Item::from_def_id_and_parts(
3142        krate_owner_def_id.to_def_id(),
3143        Some(name),
3144        ExternCrateItem { src: orig_name },
3145        cx.tcx,
3146    )]
3147}
3148
3149fn clean_use_statement<'tcx>(
3150    import: &hir::Item<'tcx>,
3151    name: Option<Symbol>,
3152    path: &hir::UsePath<'tcx>,
3153    kind: hir::UseKind,
3154    cx: &mut DocContext<'tcx>,
3155    inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
3156) -> Vec<Item> {
3157    let mut items = Vec::new();
3158    let hir::UsePath { segments, ref res, span } = *path;
3159    for res in res.present_items() {
3160        let path = hir::Path { segments, res, span };
3161        items.append(&mut clean_use_statement_inner(import, name, &path, kind, cx, inlined_names));
3162    }
3163    items
3164}
3165
3166fn clean_use_statement_inner<'tcx>(
3167    import: &hir::Item<'tcx>,
3168    name: Option<Symbol>,
3169    path: &hir::Path<'tcx>,
3170    kind: hir::UseKind,
3171    cx: &mut DocContext<'tcx>,
3172    inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
3173) -> Vec<Item> {
3174    if should_ignore_res(path.res) {
3175        return Vec::new();
3176    }
3177    // We need this comparison because some imports (for std types for example)
3178    // are "inserted" as well but directly by the compiler and they should not be
3179    // taken into account.
3180    if import.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) {
3181        return Vec::new();
3182    }
3183
3184    let visibility = cx.tcx.visibility(import.owner_id);
3185    let attrs = cx.tcx.hir_attrs(import.hir_id());
3186    let inline_attr = find_attr!(
3187        attrs,
3188        Doc(d) if d.inline.first().is_some_and(|(i, _)| *i == DocInline::Inline) => d
3189    )
3190    .and_then(|d| d.inline.first());
3191    let pub_underscore = visibility.is_public() && name == Some(kw::Underscore);
3192    let current_mod = cx.tcx.parent_module_from_def_id(import.owner_id.def_id);
3193    let import_def_id = import.owner_id.def_id;
3194
3195    // The parent of the module in which this import resides. This
3196    // is the same as `current_mod` if that's already the top
3197    // level module.
3198    let parent_mod = cx.tcx.parent_module_from_def_id(current_mod.to_local_def_id());
3199
3200    // This checks if the import can be seen from a higher level module.
3201    // In other words, it checks if the visibility is the equivalent of
3202    // `pub(super)` or higher. If the current module is the top level
3203    // module, there isn't really a parent module, which makes the results
3204    // meaningless. In this case, we make sure the answer is `false`.
3205    let is_visible_from_parent_mod =
3206        visibility.is_accessible_from(parent_mod, cx.tcx) && !current_mod.is_top_level_module();
3207
3208    if pub_underscore && let Some((_, inline_span)) = inline_attr {
3209        struct_span_code_err!(
3210            cx.tcx.dcx(),
3211            *inline_span,
3212            E0780,
3213            "anonymous imports cannot be inlined"
3214        )
3215        .with_span_label(import.span, "anonymous import")
3216        .emit();
3217    }
3218
3219    // We consider inlining the documentation of `pub use` statements, but we
3220    // forcefully don't inline if this is not public or if the
3221    // #[doc(no_inline)] attribute is present.
3222    // Don't inline doc(hidden) imports so they can be stripped at a later stage.
3223    let mut denied = cx.is_json_output()
3224        || !(visibility.is_public() || (cx.document_private() && is_visible_from_parent_mod))
3225        || pub_underscore
3226        || attrs.iter().any(|a| matches!(
3227            a,
3228            hir::Attribute::Parsed(AttributeKind::Doc(d))
3229            if d.hidden.is_some() || d.inline.first().is_some_and(|(i, _)| *i == DocInline::NoInline)
3230        ));
3231
3232    // Also check whether imports were asked to be inlined, in case we're trying to re-export a
3233    // crate in Rust 2018+
3234    let path = clean_path(path, cx);
3235    let inner = if kind == hir::UseKind::Glob {
3236        if !denied {
3237            let mut visited = DefIdSet::default();
3238            if let Some(items) = inline::try_inline_glob(
3239                cx,
3240                path.res,
3241                current_mod,
3242                &mut visited,
3243                inlined_names,
3244                import,
3245            ) {
3246                return items;
3247            }
3248        }
3249        Import::new_glob(resolve_use_source(cx, path), true)
3250    } else {
3251        let name = name.unwrap();
3252        if inline_attr.is_none()
3253            && let Res::Def(DefKind::Mod, did) = path.res
3254            && !did.is_local()
3255            && did.is_crate_root()
3256        {
3257            // if we're `pub use`ing an extern crate root, don't inline it unless we
3258            // were specifically asked for it
3259            denied = true;
3260        }
3261        if !denied
3262            && let Some(mut items) = inline::try_inline(
3263                cx,
3264                path.res,
3265                name,
3266                Some((attrs, Some(import_def_id))),
3267                &mut Default::default(),
3268            )
3269        {
3270            items.push(Item::from_def_id_and_parts(
3271                import_def_id.to_def_id(),
3272                None,
3273                ImportItem(Import::new_simple(name, resolve_use_source(cx, path), false)),
3274                cx.tcx,
3275            ));
3276            return items;
3277        }
3278        Import::new_simple(name, resolve_use_source(cx, path), true)
3279    };
3280
3281    vec![Item::from_def_id_and_parts(import_def_id.to_def_id(), None, ImportItem(inner), cx.tcx)]
3282}
3283
3284fn clean_maybe_renamed_foreign_item<'tcx>(
3285    cx: &mut DocContext<'tcx>,
3286    item: &hir::ForeignItem<'tcx>,
3287    renamed: Option<Symbol>,
3288    import_id: Option<LocalDefId>,
3289) -> Item {
3290    let def_id = item.owner_id.to_def_id();
3291    cx.with_param_env(def_id, |cx| {
3292        let kind = match item.kind {
3293            hir::ForeignItemKind::Fn(sig, idents, generics) => ForeignFunctionItem(
3294                clean_function(cx, &sig, generics, ParamsSrc::Idents(idents), def_id),
3295                sig.header.safety(),
3296            ),
3297            hir::ForeignItemKind::Static(ty, mutability, safety) => ForeignStaticItem(
3298                Static { type_: Box::new(clean_ty(ty, cx)), mutability, expr: None },
3299                safety,
3300            ),
3301            hir::ForeignItemKind::Type => ForeignTypeItem,
3302        };
3303
3304        let mut clean_item = generate_item_with_correct_attrs(
3305            cx,
3306            kind,
3307            item.owner_id.def_id.to_def_id(),
3308            item.ident.name,
3309            import_id.as_slice(),
3310            renamed,
3311        );
3312        // We also need to take into account the `extern` block (doc_)cfg attributes.
3313        let mut attrs = Attributes::from_hir(inline::load_attrs(
3314            cx.tcx,
3315            cx.tcx.hir_owner_parent(item.owner_id).owner.to_def_id(),
3316        ));
3317        attrs.merge_with(std::mem::take(&mut clean_item.inner.attrs));
3318        clean_item.inner.attrs = attrs;
3319        clean_item
3320    })
3321}
3322
3323fn clean_assoc_item_constraint<'tcx>(
3324    trait_did: DefId,
3325    constraint: &hir::AssocItemConstraint<'tcx>,
3326    cx: &mut DocContext<'tcx>,
3327) -> AssocItemConstraint {
3328    AssocItemConstraint {
3329        assoc: PathSegment {
3330            name: constraint.ident.name,
3331            args: clean_generic_args(None, constraint.gen_args, cx),
3332        },
3333        kind: match constraint.kind {
3334            hir::AssocItemConstraintKind::Equality { ref term } => {
3335                let assoc_tag = match term {
3336                    hir::Term::Ty(_) => ty::AssocTag::Type,
3337                    hir::Term::Const(_) => ty::AssocTag::Const,
3338                };
3339                let assoc_item = cx
3340                    .tcx
3341                    .associated_items(trait_did)
3342                    .find_by_ident_and_kind(cx.tcx, constraint.ident, assoc_tag, trait_did)
3343                    .map(|item| item.def_id);
3344                AssocItemConstraintKind::Equality { term: clean_hir_term(assoc_item, term, cx) }
3345            }
3346            hir::AssocItemConstraintKind::Bound { bounds } => AssocItemConstraintKind::Bound {
3347                bounds: bounds.iter().filter_map(|b| clean_generic_bound(b, cx)).collect(),
3348            },
3349        },
3350    }
3351}
3352
3353fn clean_bound_vars<'tcx>(
3354    bound_vars: &ty::List<ty::BoundVariableKind<'tcx>>,
3355    tcx: TyCtxt<'tcx>,
3356) -> Vec<GenericParamDef> {
3357    bound_vars
3358        .into_iter()
3359        .filter_map(|var| match var {
3360            ty::BoundVariableKind::Region(ty::BoundRegionKind::Named(def_id)) => {
3361                let name = tcx.item_name(def_id);
3362                if name != kw::UnderscoreLifetime {
3363                    Some(GenericParamDef::lifetime(def_id, name))
3364                } else {
3365                    None
3366                }
3367            }
3368            ty::BoundVariableKind::Ty(ty::BoundTyKind::Param(def_id)) => {
3369                let name = tcx.item_name(def_id);
3370                Some(GenericParamDef {
3371                    name,
3372                    def_id,
3373                    kind: GenericParamDefKind::Type {
3374                        bounds: ThinVec::new(),
3375                        default: None,
3376                        synthetic: false,
3377                    },
3378                })
3379            }
3380            // FIXME(non_lifetime_binders): Support higher-ranked const parameters.
3381            ty::BoundVariableKind::Const => None,
3382            _ => None,
3383        })
3384        .collect()
3385}