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