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