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