rustdoc/clean/
mod.rs

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