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