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