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