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