Skip to main content

rustdoc/clean/
mod.rs

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