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.render_options.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.render_options.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.render_options.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.render_options.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 = cx.tcx.def_kind(trait_ref.def_id()).into();
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<'tcx>(
310    constant: &hir::ConstArg<'tcx>,
311    _cx: &mut DocContext<'tcx>,
312) -> ConstantKind {
313    match &constant.kind {
314        hir::ConstArgKind::Path(qpath) => {
315            ConstantKind::Path { path: qpath_to_string(qpath).into() }
316        }
317        hir::ConstArgKind::Anon(anon) => ConstantKind::Anonymous { body: anon.body },
318        hir::ConstArgKind::Infer(..) => ConstantKind::Infer,
319    }
320}
321
322pub(crate) fn clean_middle_const<'tcx>(
323    constant: ty::Binder<'tcx, ty::Const<'tcx>>,
324    _cx: &mut DocContext<'tcx>,
325) -> ConstantKind {
326    // FIXME: instead of storing the stringified expression, store `self` directly instead.
327    ConstantKind::TyConst { expr: constant.skip_binder().to_string().into() }
328}
329
330pub(crate) fn clean_middle_region<'tcx>(
331    region: ty::Region<'tcx>,
332    cx: &mut DocContext<'tcx>,
333) -> Option<Lifetime> {
334    region.get_name(cx.tcx).map(Lifetime)
335}
336
337fn clean_where_predicate<'tcx>(
338    predicate: &hir::WherePredicate<'tcx>,
339    cx: &mut DocContext<'tcx>,
340) -> Option<WherePredicate> {
341    if !predicate.kind.in_where_clause() {
342        return None;
343    }
344    Some(match predicate.kind {
345        hir::WherePredicateKind::BoundPredicate(wbp) => {
346            let bound_params = wbp
347                .bound_generic_params
348                .iter()
349                .map(|param| clean_generic_param(cx, None, param))
350                .collect();
351            WherePredicate::BoundPredicate {
352                ty: clean_ty(wbp.bounded_ty, cx),
353                bounds: wbp.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
354                bound_params,
355            }
356        }
357
358        hir::WherePredicateKind::RegionPredicate(wrp) => WherePredicate::RegionPredicate {
359            lifetime: clean_lifetime(wrp.lifetime, cx),
360            bounds: wrp.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(),
361        },
362
363        // We should never actually reach this case because these predicates should've already been
364        // rejected in an earlier compiler pass. This feature isn't fully implemented (#20041).
365        hir::WherePredicateKind::EqPredicate(_) => bug!("EqPredicate"),
366    })
367}
368
369pub(crate) fn clean_predicate<'tcx>(
370    predicate: ty::Clause<'tcx>,
371    cx: &mut DocContext<'tcx>,
372) -> Option<WherePredicate> {
373    let bound_predicate = predicate.kind();
374    match bound_predicate.skip_binder() {
375        ty::ClauseKind::Trait(pred) => clean_poly_trait_predicate(bound_predicate.rebind(pred), cx),
376        ty::ClauseKind::RegionOutlives(pred) => Some(clean_region_outlives_predicate(pred, cx)),
377        ty::ClauseKind::TypeOutlives(pred) => {
378            Some(clean_type_outlives_predicate(bound_predicate.rebind(pred), cx))
379        }
380        ty::ClauseKind::Projection(pred) => {
381            Some(clean_projection_predicate(bound_predicate.rebind(pred), cx))
382        }
383        // FIXME(generic_const_exprs): should this do something?
384        ty::ClauseKind::ConstEvaluatable(..)
385        | ty::ClauseKind::WellFormed(..)
386        | ty::ClauseKind::ConstArgHasType(..)
387        | ty::ClauseKind::UnstableFeature(..)
388        // FIXME(const_trait_impl): We can probably use this `HostEffect` pred to render `~const`.
389        | ty::ClauseKind::HostEffect(_) => None,
390    }
391}
392
393fn clean_poly_trait_predicate<'tcx>(
394    pred: ty::PolyTraitPredicate<'tcx>,
395    cx: &mut DocContext<'tcx>,
396) -> Option<WherePredicate> {
397    // `T: [const] Destruct` is hidden because `T: Destruct` is a no-op.
398    // FIXME(const_trait_impl) check constness
399    if Some(pred.skip_binder().def_id()) == cx.tcx.lang_items().destruct_trait() {
400        return None;
401    }
402
403    let poly_trait_ref = pred.map_bound(|pred| pred.trait_ref);
404    Some(WherePredicate::BoundPredicate {
405        ty: clean_middle_ty(poly_trait_ref.self_ty(), cx, None, None),
406        bounds: vec![clean_poly_trait_ref_with_constraints(cx, poly_trait_ref, ThinVec::new())],
407        bound_params: Vec::new(),
408    })
409}
410
411fn clean_region_outlives_predicate<'tcx>(
412    pred: ty::RegionOutlivesPredicate<'tcx>,
413    cx: &mut DocContext<'tcx>,
414) -> WherePredicate {
415    let ty::OutlivesPredicate(a, b) = pred;
416
417    WherePredicate::RegionPredicate {
418        lifetime: clean_middle_region(a, cx).expect("failed to clean lifetime"),
419        bounds: vec![GenericBound::Outlives(
420            clean_middle_region(b, cx).expect("failed to clean bounds"),
421        )],
422    }
423}
424
425fn clean_type_outlives_predicate<'tcx>(
426    pred: ty::Binder<'tcx, ty::TypeOutlivesPredicate<'tcx>>,
427    cx: &mut DocContext<'tcx>,
428) -> WherePredicate {
429    let ty::OutlivesPredicate(ty, lt) = pred.skip_binder();
430
431    WherePredicate::BoundPredicate {
432        ty: clean_middle_ty(pred.rebind(ty), cx, None, None),
433        bounds: vec![GenericBound::Outlives(
434            clean_middle_region(lt, cx).expect("failed to clean lifetimes"),
435        )],
436        bound_params: Vec::new(),
437    }
438}
439
440fn clean_middle_term<'tcx>(
441    term: ty::Binder<'tcx, ty::Term<'tcx>>,
442    cx: &mut DocContext<'tcx>,
443) -> Term {
444    match term.skip_binder().kind() {
445        ty::TermKind::Ty(ty) => Term::Type(clean_middle_ty(term.rebind(ty), cx, None, None)),
446        ty::TermKind::Const(c) => Term::Constant(clean_middle_const(term.rebind(c), cx)),
447    }
448}
449
450fn clean_hir_term<'tcx>(term: &hir::Term<'tcx>, cx: &mut DocContext<'tcx>) -> Term {
451    match term {
452        hir::Term::Ty(ty) => Term::Type(clean_ty(ty, cx)),
453        hir::Term::Const(c) => {
454            let ct = lower_const_arg_for_rustdoc(cx.tcx, c, FeedConstTy::No);
455            Term::Constant(clean_middle_const(ty::Binder::dummy(ct), cx))
456        }
457    }
458}
459
460fn clean_projection_predicate<'tcx>(
461    pred: ty::Binder<'tcx, ty::ProjectionPredicate<'tcx>>,
462    cx: &mut DocContext<'tcx>,
463) -> WherePredicate {
464    WherePredicate::EqPredicate {
465        lhs: clean_projection(pred.map_bound(|p| p.projection_term), cx, None),
466        rhs: clean_middle_term(pred.map_bound(|p| p.term), cx),
467    }
468}
469
470fn clean_projection<'tcx>(
471    proj: ty::Binder<'tcx, ty::AliasTerm<'tcx>>,
472    cx: &mut DocContext<'tcx>,
473    parent_def_id: Option<DefId>,
474) -> QPathData {
475    let trait_ = clean_trait_ref_with_constraints(
476        cx,
477        proj.map_bound(|proj| proj.trait_ref(cx.tcx)),
478        ThinVec::new(),
479    );
480    let self_type = clean_middle_ty(proj.map_bound(|proj| proj.self_ty()), cx, None, None);
481    let self_def_id = match parent_def_id {
482        Some(parent_def_id) => cx.tcx.opt_parent(parent_def_id).or(Some(parent_def_id)),
483        None => self_type.def_id(&cx.cache),
484    };
485    let should_fully_qualify = should_fully_qualify_path(self_def_id, &trait_, &self_type);
486
487    QPathData {
488        assoc: projection_to_path_segment(proj, cx),
489        self_type,
490        should_fully_qualify,
491        trait_: Some(trait_),
492    }
493}
494
495fn should_fully_qualify_path(self_def_id: Option<DefId>, trait_: &Path, self_type: &Type) -> bool {
496    !trait_.segments.is_empty()
497        && self_def_id
498            .zip(Some(trait_.def_id()))
499            .map_or(!self_type.is_self_type(), |(id, trait_)| id != trait_)
500}
501
502fn projection_to_path_segment<'tcx>(
503    proj: ty::Binder<'tcx, ty::AliasTerm<'tcx>>,
504    cx: &mut DocContext<'tcx>,
505) -> PathSegment {
506    let def_id = proj.skip_binder().def_id;
507    let generics = cx.tcx.generics_of(def_id);
508    PathSegment {
509        name: cx.tcx.item_name(def_id),
510        args: GenericArgs::AngleBracketed {
511            args: clean_middle_generic_args(
512                cx,
513                proj.map_bound(|ty| &ty.args[generics.parent_count..]),
514                false,
515                def_id,
516            ),
517            constraints: Default::default(),
518        },
519    }
520}
521
522fn clean_generic_param_def(
523    def: &ty::GenericParamDef,
524    defaults: ParamDefaults,
525    cx: &mut DocContext<'_>,
526) -> GenericParamDef {
527    let (name, kind) = match def.kind {
528        ty::GenericParamDefKind::Lifetime => {
529            (def.name, GenericParamDefKind::Lifetime { outlives: ThinVec::new() })
530        }
531        ty::GenericParamDefKind::Type { has_default, synthetic, .. } => {
532            let default = if let ParamDefaults::Yes = defaults
533                && has_default
534            {
535                Some(clean_middle_ty(
536                    ty::Binder::dummy(cx.tcx.type_of(def.def_id).instantiate_identity()),
537                    cx,
538                    Some(def.def_id),
539                    None,
540                ))
541            } else {
542                None
543            };
544            (
545                def.name,
546                GenericParamDefKind::Type {
547                    bounds: ThinVec::new(), // These are filled in from the where-clauses.
548                    default: default.map(Box::new),
549                    synthetic,
550                },
551            )
552        }
553        ty::GenericParamDefKind::Const { has_default } => (
554            def.name,
555            GenericParamDefKind::Const {
556                ty: Box::new(clean_middle_ty(
557                    ty::Binder::dummy(
558                        cx.tcx
559                            .type_of(def.def_id)
560                            .no_bound_vars()
561                            .expect("const parameter types cannot be generic"),
562                    ),
563                    cx,
564                    Some(def.def_id),
565                    None,
566                )),
567                default: if let ParamDefaults::Yes = defaults
568                    && has_default
569                {
570                    Some(Box::new(
571                        cx.tcx.const_param_default(def.def_id).instantiate_identity().to_string(),
572                    ))
573                } else {
574                    None
575                },
576            },
577        ),
578    };
579
580    GenericParamDef { name, def_id: def.def_id, kind }
581}
582
583/// Whether to clean generic parameter defaults or not.
584enum ParamDefaults {
585    Yes,
586    No,
587}
588
589fn clean_generic_param<'tcx>(
590    cx: &mut DocContext<'tcx>,
591    generics: Option<&hir::Generics<'tcx>>,
592    param: &hir::GenericParam<'tcx>,
593) -> GenericParamDef {
594    let (name, kind) = match param.kind {
595        hir::GenericParamKind::Lifetime { .. } => {
596            let outlives = if let Some(generics) = generics {
597                generics
598                    .outlives_for_param(param.def_id)
599                    .filter(|bp| !bp.in_where_clause)
600                    .flat_map(|bp| bp.bounds)
601                    .map(|bound| match bound {
602                        hir::GenericBound::Outlives(lt) => clean_lifetime(lt, cx),
603                        _ => panic!(),
604                    })
605                    .collect()
606            } else {
607                ThinVec::new()
608            };
609            (param.name.ident().name, GenericParamDefKind::Lifetime { outlives })
610        }
611        hir::GenericParamKind::Type { ref default, synthetic } => {
612            let bounds = if let Some(generics) = generics {
613                generics
614                    .bounds_for_param(param.def_id)
615                    .filter(|bp| bp.origin != PredicateOrigin::WhereClause)
616                    .flat_map(|bp| bp.bounds)
617                    .filter_map(|x| clean_generic_bound(x, cx))
618                    .collect()
619            } else {
620                ThinVec::new()
621            };
622            (
623                param.name.ident().name,
624                GenericParamDefKind::Type {
625                    bounds,
626                    default: default.map(|t| clean_ty(t, cx)).map(Box::new),
627                    synthetic,
628                },
629            )
630        }
631        hir::GenericParamKind::Const { ty, default } => (
632            param.name.ident().name,
633            GenericParamDefKind::Const {
634                ty: Box::new(clean_ty(ty, cx)),
635                default: default.map(|ct| {
636                    Box::new(lower_const_arg_for_rustdoc(cx.tcx, ct, FeedConstTy::No).to_string())
637                }),
638            },
639        ),
640    };
641
642    GenericParamDef { name, def_id: param.def_id.to_def_id(), kind }
643}
644
645/// Synthetic type-parameters are inserted after normal ones.
646/// In order for normal parameters to be able to refer to synthetic ones,
647/// scans them first.
648fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool {
649    match param.kind {
650        hir::GenericParamKind::Type { synthetic, .. } => synthetic,
651        _ => false,
652    }
653}
654
655/// This can happen for `async fn`, e.g. `async fn f<'_>(&'_ self)`.
656///
657/// See `lifetime_to_generic_param` in `rustc_ast_lowering` for more information.
658fn is_elided_lifetime(param: &hir::GenericParam<'_>) -> bool {
659    matches!(
660        param.kind,
661        hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided(_) }
662    )
663}
664
665pub(crate) fn clean_generics<'tcx>(
666    gens: &hir::Generics<'tcx>,
667    cx: &mut DocContext<'tcx>,
668) -> Generics {
669    let impl_trait_params = gens
670        .params
671        .iter()
672        .filter(|param| is_impl_trait(param))
673        .map(|param| {
674            let param = clean_generic_param(cx, Some(gens), param);
675            match param.kind {
676                GenericParamDefKind::Lifetime { .. } => unreachable!(),
677                GenericParamDefKind::Type { ref bounds, .. } => {
678                    cx.impl_trait_bounds.insert(param.def_id.into(), bounds.to_vec());
679                }
680                GenericParamDefKind::Const { .. } => unreachable!(),
681            }
682            param
683        })
684        .collect::<Vec<_>>();
685
686    let mut bound_predicates = FxIndexMap::default();
687    let mut region_predicates = FxIndexMap::default();
688    let mut eq_predicates = ThinVec::default();
689    for pred in gens.predicates.iter().filter_map(|x| clean_where_predicate(x, cx)) {
690        match pred {
691            WherePredicate::BoundPredicate { ty, bounds, bound_params } => {
692                match bound_predicates.entry(ty) {
693                    IndexEntry::Vacant(v) => {
694                        v.insert((bounds, bound_params));
695                    }
696                    IndexEntry::Occupied(mut o) => {
697                        // we merge both bounds.
698                        for bound in bounds {
699                            if !o.get().0.contains(&bound) {
700                                o.get_mut().0.push(bound);
701                            }
702                        }
703                        for bound_param in bound_params {
704                            if !o.get().1.contains(&bound_param) {
705                                o.get_mut().1.push(bound_param);
706                            }
707                        }
708                    }
709                }
710            }
711            WherePredicate::RegionPredicate { lifetime, bounds } => {
712                match region_predicates.entry(lifetime) {
713                    IndexEntry::Vacant(v) => {
714                        v.insert(bounds);
715                    }
716                    IndexEntry::Occupied(mut o) => {
717                        // we merge both bounds.
718                        for bound in bounds {
719                            if !o.get().contains(&bound) {
720                                o.get_mut().push(bound);
721                            }
722                        }
723                    }
724                }
725            }
726            WherePredicate::EqPredicate { lhs, rhs } => {
727                eq_predicates.push(WherePredicate::EqPredicate { lhs, rhs });
728            }
729        }
730    }
731
732    let mut params = ThinVec::with_capacity(gens.params.len());
733    // In this loop, we gather the generic parameters (`<'a, B: 'a>`) and check if they have
734    // bounds in the where predicates. If so, we move their bounds into the where predicates
735    // while also preventing duplicates.
736    for p in gens.params.iter().filter(|p| !is_impl_trait(p) && !is_elided_lifetime(p)) {
737        let mut p = clean_generic_param(cx, Some(gens), p);
738        match &mut p.kind {
739            GenericParamDefKind::Lifetime { outlives } => {
740                if let Some(region_pred) = region_predicates.get_mut(&Lifetime(p.name)) {
741                    // We merge bounds in the `where` clause.
742                    for outlive in outlives.drain(..) {
743                        let outlive = GenericBound::Outlives(outlive);
744                        if !region_pred.contains(&outlive) {
745                            region_pred.push(outlive);
746                        }
747                    }
748                }
749            }
750            GenericParamDefKind::Type { bounds, synthetic: false, .. } => {
751                if let Some(bound_pred) = bound_predicates.get_mut(&Type::Generic(p.name)) {
752                    // We merge bounds in the `where` clause.
753                    for bound in bounds.drain(..) {
754                        if !bound_pred.0.contains(&bound) {
755                            bound_pred.0.push(bound);
756                        }
757                    }
758                }
759            }
760            GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => {
761                // nothing to do here.
762            }
763        }
764        params.push(p);
765    }
766    params.extend(impl_trait_params);
767
768    Generics {
769        params,
770        where_predicates: bound_predicates
771            .into_iter()
772            .map(|(ty, (bounds, bound_params))| WherePredicate::BoundPredicate {
773                ty,
774                bounds,
775                bound_params,
776            })
777            .chain(
778                region_predicates
779                    .into_iter()
780                    .map(|(lifetime, bounds)| WherePredicate::RegionPredicate { lifetime, bounds }),
781            )
782            .chain(eq_predicates)
783            .collect(),
784    }
785}
786
787fn clean_ty_generics<'tcx>(cx: &mut DocContext<'tcx>, def_id: DefId) -> Generics {
788    clean_ty_generics_inner(cx, cx.tcx.generics_of(def_id), cx.tcx.explicit_predicates_of(def_id))
789}
790
791fn clean_ty_generics_inner<'tcx>(
792    cx: &mut DocContext<'tcx>,
793    gens: &ty::Generics,
794    preds: ty::GenericPredicates<'tcx>,
795) -> Generics {
796    // Don't populate `cx.impl_trait_bounds` before cleaning where clauses,
797    // since `clean_predicate` would consume them.
798    let mut impl_trait = BTreeMap::<u32, Vec<GenericBound>>::default();
799
800    let params: ThinVec<_> = gens
801        .own_params
802        .iter()
803        .filter(|param| match param.kind {
804            ty::GenericParamDefKind::Lifetime => !param.is_anonymous_lifetime(),
805            ty::GenericParamDefKind::Type { synthetic, .. } => {
806                if param.name == kw::SelfUpper {
807                    debug_assert_eq!(param.index, 0);
808                    return false;
809                }
810                if synthetic {
811                    impl_trait.insert(param.index, vec![]);
812                    return false;
813                }
814                true
815            }
816            ty::GenericParamDefKind::Const { .. } => true,
817        })
818        .map(|param| clean_generic_param_def(param, ParamDefaults::Yes, cx))
819        .collect();
820
821    // param index -> [(trait DefId, associated type name & generics, term)]
822    let mut impl_trait_proj =
823        FxHashMap::<u32, Vec<(DefId, PathSegment, ty::Binder<'_, ty::Term<'_>>)>>::default();
824
825    let where_predicates = preds
826        .predicates
827        .iter()
828        .flat_map(|(pred, _)| {
829            let mut proj_pred = None;
830            let param_idx = {
831                let bound_p = pred.kind();
832                match bound_p.skip_binder() {
833                    ty::ClauseKind::Trait(pred) if let ty::Param(param) = pred.self_ty().kind() => {
834                        Some(param.index)
835                    }
836                    ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty, _reg))
837                        if let ty::Param(param) = ty.kind() =>
838                    {
839                        Some(param.index)
840                    }
841                    ty::ClauseKind::Projection(p)
842                        if let ty::Param(param) = p.projection_term.self_ty().kind() =>
843                    {
844                        proj_pred = Some(bound_p.rebind(p));
845                        Some(param.index)
846                    }
847                    _ => None,
848                }
849            };
850
851            if let Some(param_idx) = param_idx
852                && let Some(bounds) = impl_trait.get_mut(&param_idx)
853            {
854                let pred = clean_predicate(*pred, cx)?;
855
856                bounds.extend(pred.get_bounds().into_iter().flatten().cloned());
857
858                if let Some(pred) = proj_pred {
859                    let lhs = clean_projection(pred.map_bound(|p| p.projection_term), cx, None);
860                    impl_trait_proj.entry(param_idx).or_default().push((
861                        lhs.trait_.unwrap().def_id(),
862                        lhs.assoc,
863                        pred.map_bound(|p| p.term),
864                    ));
865                }
866
867                return None;
868            }
869
870            Some(pred)
871        })
872        .collect::<Vec<_>>();
873
874    for (idx, mut bounds) in impl_trait {
875        let mut has_sized = false;
876        bounds.retain(|b| {
877            if b.is_sized_bound(cx) {
878                has_sized = true;
879                false
880            } else if b.is_meta_sized_bound(cx) {
881                // FIXME(sized-hierarchy): Always skip `MetaSized` bounds so that only `?Sized`
882                // is shown and none of the new sizedness traits leak into documentation.
883                false
884            } else {
885                true
886            }
887        });
888        if !has_sized {
889            bounds.push(GenericBound::maybe_sized(cx));
890        }
891
892        // Move trait bounds to the front.
893        bounds.sort_by_key(|b| !b.is_trait_bound());
894
895        // Add back a `Sized` bound if there are no *trait* bounds remaining (incl. `?Sized`).
896        // Since all potential trait bounds are at the front we can just check the first bound.
897        if bounds.first().is_none_or(|b| !b.is_trait_bound()) {
898            bounds.insert(0, GenericBound::sized(cx));
899        }
900
901        if let Some(proj) = impl_trait_proj.remove(&idx) {
902            for (trait_did, name, rhs) in proj {
903                let rhs = clean_middle_term(rhs, cx);
904                simplify::merge_bounds(cx, &mut bounds, trait_did, name, &rhs);
905            }
906        }
907
908        cx.impl_trait_bounds.insert(idx.into(), bounds);
909    }
910
911    // Now that `cx.impl_trait_bounds` is populated, we can process
912    // remaining predicates which could contain `impl Trait`.
913    let where_predicates =
914        where_predicates.into_iter().flat_map(|p| clean_predicate(*p, cx)).collect();
915
916    let mut generics = Generics { params, where_predicates };
917    simplify::sized_bounds(cx, &mut generics);
918    generics.where_predicates = simplify::where_clauses(cx, generics.where_predicates);
919    generics
920}
921
922fn clean_ty_alias_inner_type<'tcx>(
923    ty: Ty<'tcx>,
924    cx: &mut DocContext<'tcx>,
925    ret: &mut Vec<Item>,
926) -> Option<TypeAliasInnerType> {
927    let ty::Adt(adt_def, args) = ty.kind() else {
928        return None;
929    };
930
931    if !adt_def.did().is_local() {
932        cx.with_param_env(adt_def.did(), |cx| {
933            inline::build_impls(cx, adt_def.did(), None, ret);
934        });
935    }
936
937    Some(if adt_def.is_enum() {
938        let variants: rustc_index::IndexVec<_, _> = adt_def
939            .variants()
940            .iter()
941            .map(|variant| clean_variant_def_with_args(variant, args, cx))
942            .collect();
943
944        if !adt_def.did().is_local() {
945            inline::record_extern_fqn(cx, adt_def.did(), ItemType::Enum);
946        }
947
948        TypeAliasInnerType::Enum {
949            variants,
950            is_non_exhaustive: adt_def.is_variant_list_non_exhaustive(),
951        }
952    } else {
953        let variant = adt_def
954            .variants()
955            .iter()
956            .next()
957            .unwrap_or_else(|| bug!("a struct or union should always have one variant def"));
958
959        let fields: Vec<_> =
960            clean_variant_def_with_args(variant, args, cx).kind.inner_items().cloned().collect();
961
962        if adt_def.is_struct() {
963            if !adt_def.did().is_local() {
964                inline::record_extern_fqn(cx, adt_def.did(), ItemType::Struct);
965            }
966            TypeAliasInnerType::Struct { ctor_kind: variant.ctor_kind(), fields }
967        } else {
968            if !adt_def.did().is_local() {
969                inline::record_extern_fqn(cx, adt_def.did(), ItemType::Union);
970            }
971            TypeAliasInnerType::Union { fields }
972        }
973    })
974}
975
976fn clean_proc_macro<'tcx>(
977    item: &hir::Item<'tcx>,
978    name: &mut Symbol,
979    kind: MacroKind,
980    cx: &mut DocContext<'tcx>,
981) -> ItemKind {
982    if kind != MacroKind::Derive {
983        return ProcMacroItem(ProcMacro { kind, helpers: vec![] });
984    }
985    let attrs = cx.tcx.hir_attrs(item.hir_id());
986    let Some((trait_name, helper_attrs)) = find_attr!(attrs, AttributeKind::ProcMacroDerive { trait_name, helper_attrs, ..} => (*trait_name, helper_attrs))
987    else {
988        return ProcMacroItem(ProcMacro { kind, helpers: vec![] });
989    };
990    *name = trait_name;
991    let helpers = helper_attrs.iter().copied().collect();
992
993    ProcMacroItem(ProcMacro { kind, helpers })
994}
995
996fn clean_fn_or_proc_macro<'tcx>(
997    item: &hir::Item<'tcx>,
998    sig: &hir::FnSig<'tcx>,
999    generics: &hir::Generics<'tcx>,
1000    body_id: hir::BodyId,
1001    name: &mut Symbol,
1002    cx: &mut DocContext<'tcx>,
1003) -> ItemKind {
1004    let attrs = cx.tcx.hir_attrs(item.hir_id());
1005    let macro_kind = if find_attr!(attrs, AttributeKind::ProcMacro(..)) {
1006        Some(MacroKind::Bang)
1007    } else if find_attr!(attrs, AttributeKind::ProcMacroDerive { .. }) {
1008        Some(MacroKind::Derive)
1009    } else if find_attr!(attrs, AttributeKind::ProcMacroAttribute(..)) {
1010        Some(MacroKind::Attr)
1011    } else {
1012        None
1013    };
1014
1015    match macro_kind {
1016        Some(kind) => clean_proc_macro(item, name, kind, cx),
1017        None => {
1018            let mut func = clean_function(cx, sig, generics, ParamsSrc::Body(body_id));
1019            clean_fn_decl_legacy_const_generics(&mut func, attrs);
1020            FunctionItem(func)
1021        }
1022    }
1023}
1024
1025/// This is needed to make it more "readable" when documenting functions using
1026/// `rustc_legacy_const_generics`. More information in
1027/// <https://github.com/rust-lang/rust/issues/83167>.
1028fn clean_fn_decl_legacy_const_generics(func: &mut Function, attrs: &[hir::Attribute]) {
1029    for meta_item_list in attrs
1030        .iter()
1031        .filter(|a| a.has_name(sym::rustc_legacy_const_generics))
1032        .filter_map(|a| a.meta_item_list())
1033    {
1034        for (pos, literal) in meta_item_list.iter().filter_map(|meta| meta.lit()).enumerate() {
1035            match literal.kind {
1036                ast::LitKind::Int(a, _) => {
1037                    let GenericParamDef { name, kind, .. } = func.generics.params.remove(0);
1038                    if let GenericParamDefKind::Const { ty, .. } = kind {
1039                        func.decl.inputs.insert(
1040                            a.get() as _,
1041                            Parameter { name: Some(name), type_: *ty, is_const: true },
1042                        );
1043                    } else {
1044                        panic!("unexpected non const in position {pos}");
1045                    }
1046                }
1047                _ => panic!("invalid arg index"),
1048            }
1049        }
1050    }
1051}
1052
1053enum ParamsSrc<'tcx> {
1054    Body(hir::BodyId),
1055    Idents(&'tcx [Option<Ident>]),
1056}
1057
1058fn clean_function<'tcx>(
1059    cx: &mut DocContext<'tcx>,
1060    sig: &hir::FnSig<'tcx>,
1061    generics: &hir::Generics<'tcx>,
1062    params: ParamsSrc<'tcx>,
1063) -> Box<Function> {
1064    let (generics, decl) = enter_impl_trait(cx, |cx| {
1065        // NOTE: Generics must be cleaned before params.
1066        let generics = clean_generics(generics, cx);
1067        let params = match params {
1068            ParamsSrc::Body(body_id) => clean_params_via_body(cx, sig.decl.inputs, body_id),
1069            // Let's not perpetuate anon params from Rust 2015; use `_` for them.
1070            ParamsSrc::Idents(idents) => clean_params(cx, sig.decl.inputs, idents, |ident| {
1071                Some(ident.map_or(kw::Underscore, |ident| ident.name))
1072            }),
1073        };
1074        let decl = clean_fn_decl_with_params(cx, sig.decl, Some(&sig.header), params);
1075        (generics, decl)
1076    });
1077    Box::new(Function { decl, generics })
1078}
1079
1080fn clean_params<'tcx>(
1081    cx: &mut DocContext<'tcx>,
1082    types: &[hir::Ty<'tcx>],
1083    idents: &[Option<Ident>],
1084    postprocess: impl Fn(Option<Ident>) -> Option<Symbol>,
1085) -> Vec<Parameter> {
1086    types
1087        .iter()
1088        .enumerate()
1089        .map(|(i, ty)| Parameter {
1090            name: postprocess(idents[i]),
1091            type_: clean_ty(ty, cx),
1092            is_const: false,
1093        })
1094        .collect()
1095}
1096
1097fn clean_params_via_body<'tcx>(
1098    cx: &mut DocContext<'tcx>,
1099    types: &[hir::Ty<'tcx>],
1100    body_id: hir::BodyId,
1101) -> Vec<Parameter> {
1102    types
1103        .iter()
1104        .zip(cx.tcx.hir_body(body_id).params)
1105        .map(|(ty, param)| Parameter {
1106            name: Some(name_from_pat(param.pat)),
1107            type_: clean_ty(ty, cx),
1108            is_const: false,
1109        })
1110        .collect()
1111}
1112
1113fn clean_fn_decl_with_params<'tcx>(
1114    cx: &mut DocContext<'tcx>,
1115    decl: &hir::FnDecl<'tcx>,
1116    header: Option<&hir::FnHeader>,
1117    params: Vec<Parameter>,
1118) -> FnDecl {
1119    let mut output = match decl.output {
1120        hir::FnRetTy::Return(typ) => clean_ty(typ, cx),
1121        hir::FnRetTy::DefaultReturn(..) => Type::Tuple(Vec::new()),
1122    };
1123    if let Some(header) = header
1124        && header.is_async()
1125    {
1126        output = output.sugared_async_return_type();
1127    }
1128    FnDecl { inputs: params, output, c_variadic: decl.c_variadic }
1129}
1130
1131fn clean_poly_fn_sig<'tcx>(
1132    cx: &mut DocContext<'tcx>,
1133    did: Option<DefId>,
1134    sig: ty::PolyFnSig<'tcx>,
1135) -> FnDecl {
1136    let mut output = clean_middle_ty(sig.output(), cx, None, None);
1137
1138    // If the return type isn't an `impl Trait`, we can safely assume that this
1139    // function isn't async without needing to execute the query `asyncness` at
1140    // all which gives us a noticeable performance boost.
1141    if let Some(did) = did
1142        && let Type::ImplTrait(_) = output
1143        && cx.tcx.asyncness(did).is_async()
1144    {
1145        output = output.sugared_async_return_type();
1146    }
1147
1148    let mut idents = did.map(|did| cx.tcx.fn_arg_idents(did)).unwrap_or_default().iter().copied();
1149
1150    // If this comes from a fn item, let's not perpetuate anon params from Rust 2015; use `_` for them.
1151    // If this comes from a fn ptr ty, we just keep params unnamed since it's more conventional stylistically.
1152    // Since the param name is not part of the semantic type, these params never bear a name unlike
1153    // in the HIR case, thus we can't perform any fancy fallback logic unlike `clean_bare_fn_ty`.
1154    let fallback = did.map(|_| kw::Underscore);
1155
1156    let params = sig
1157        .inputs()
1158        .iter()
1159        .map(|ty| Parameter {
1160            name: idents.next().flatten().map(|ident| ident.name).or(fallback),
1161            type_: clean_middle_ty(ty.map_bound(|ty| *ty), cx, None, None),
1162            is_const: false,
1163        })
1164        .collect();
1165
1166    FnDecl { inputs: params, output, c_variadic: sig.skip_binder().c_variadic }
1167}
1168
1169fn clean_trait_ref<'tcx>(trait_ref: &hir::TraitRef<'tcx>, cx: &mut DocContext<'tcx>) -> Path {
1170    let path = clean_path(trait_ref.path, cx);
1171    register_res(cx, path.res);
1172    path
1173}
1174
1175fn clean_poly_trait_ref<'tcx>(
1176    poly_trait_ref: &hir::PolyTraitRef<'tcx>,
1177    cx: &mut DocContext<'tcx>,
1178) -> PolyTrait {
1179    PolyTrait {
1180        trait_: clean_trait_ref(&poly_trait_ref.trait_ref, cx),
1181        generic_params: poly_trait_ref
1182            .bound_generic_params
1183            .iter()
1184            .filter(|p| !is_elided_lifetime(p))
1185            .map(|x| clean_generic_param(cx, None, x))
1186            .collect(),
1187    }
1188}
1189
1190fn clean_trait_item<'tcx>(trait_item: &hir::TraitItem<'tcx>, cx: &mut DocContext<'tcx>) -> Item {
1191    let local_did = trait_item.owner_id.to_def_id();
1192    cx.with_param_env(local_did, |cx| {
1193        let inner = match trait_item.kind {
1194            hir::TraitItemKind::Const(ty, Some(default)) => {
1195                ProvidedAssocConstItem(Box::new(Constant {
1196                    generics: enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx)),
1197                    kind: ConstantKind::Local { def_id: local_did, body: default },
1198                    type_: clean_ty(ty, cx),
1199                }))
1200            }
1201            hir::TraitItemKind::Const(ty, None) => {
1202                let generics = enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx));
1203                RequiredAssocConstItem(generics, Box::new(clean_ty(ty, cx)))
1204            }
1205            hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => {
1206                let m = clean_function(cx, sig, trait_item.generics, ParamsSrc::Body(body));
1207                MethodItem(m, None)
1208            }
1209            hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(idents)) => {
1210                let m = clean_function(cx, sig, trait_item.generics, ParamsSrc::Idents(idents));
1211                RequiredMethodItem(m)
1212            }
1213            hir::TraitItemKind::Type(bounds, Some(default)) => {
1214                let generics = enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx));
1215                let bounds = bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect();
1216                let item_type =
1217                    clean_middle_ty(ty::Binder::dummy(lower_ty(cx.tcx, default)), cx, None, None);
1218                AssocTypeItem(
1219                    Box::new(TypeAlias {
1220                        type_: clean_ty(default, cx),
1221                        generics,
1222                        inner_type: None,
1223                        item_type: Some(item_type),
1224                    }),
1225                    bounds,
1226                )
1227            }
1228            hir::TraitItemKind::Type(bounds, None) => {
1229                let generics = enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx));
1230                let bounds = bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect();
1231                RequiredAssocTypeItem(generics, bounds)
1232            }
1233        };
1234        Item::from_def_id_and_parts(local_did, Some(trait_item.ident.name), inner, cx)
1235    })
1236}
1237
1238pub(crate) fn clean_impl_item<'tcx>(
1239    impl_: &hir::ImplItem<'tcx>,
1240    cx: &mut DocContext<'tcx>,
1241) -> Item {
1242    let local_did = impl_.owner_id.to_def_id();
1243    cx.with_param_env(local_did, |cx| {
1244        let inner = match impl_.kind {
1245            hir::ImplItemKind::Const(ty, expr) => ImplAssocConstItem(Box::new(Constant {
1246                generics: clean_generics(impl_.generics, cx),
1247                kind: ConstantKind::Local { def_id: local_did, body: expr },
1248                type_: clean_ty(ty, cx),
1249            })),
1250            hir::ImplItemKind::Fn(ref sig, body) => {
1251                let m = clean_function(cx, sig, impl_.generics, ParamsSrc::Body(body));
1252                let defaultness = match impl_.impl_kind {
1253                    hir::ImplItemImplKind::Inherent { .. } => hir::Defaultness::Final,
1254                    hir::ImplItemImplKind::Trait { defaultness, .. } => defaultness,
1255                };
1256                MethodItem(m, Some(defaultness))
1257            }
1258            hir::ImplItemKind::Type(hir_ty) => {
1259                let type_ = clean_ty(hir_ty, cx);
1260                let generics = clean_generics(impl_.generics, cx);
1261                let item_type =
1262                    clean_middle_ty(ty::Binder::dummy(lower_ty(cx.tcx, hir_ty)), cx, None, None);
1263                AssocTypeItem(
1264                    Box::new(TypeAlias {
1265                        type_,
1266                        generics,
1267                        inner_type: None,
1268                        item_type: Some(item_type),
1269                    }),
1270                    Vec::new(),
1271                )
1272            }
1273        };
1274
1275        Item::from_def_id_and_parts(local_did, Some(impl_.ident.name), inner, cx)
1276    })
1277}
1278
1279pub(crate) fn clean_middle_assoc_item(assoc_item: &ty::AssocItem, cx: &mut DocContext<'_>) -> Item {
1280    let tcx = cx.tcx;
1281    let kind = match assoc_item.kind {
1282        ty::AssocKind::Const { .. } => {
1283            let ty = clean_middle_ty(
1284                ty::Binder::dummy(tcx.type_of(assoc_item.def_id).instantiate_identity()),
1285                cx,
1286                Some(assoc_item.def_id),
1287                None,
1288            );
1289
1290            let mut generics = clean_ty_generics(cx, assoc_item.def_id);
1291            simplify::move_bounds_to_generic_parameters(&mut generics);
1292
1293            match assoc_item.container {
1294                ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
1295                    ImplAssocConstItem(Box::new(Constant {
1296                        generics,
1297                        kind: ConstantKind::Extern { def_id: assoc_item.def_id },
1298                        type_: ty,
1299                    }))
1300                }
1301                ty::AssocContainer::Trait => {
1302                    if tcx.defaultness(assoc_item.def_id).has_value() {
1303                        ProvidedAssocConstItem(Box::new(Constant {
1304                            generics,
1305                            kind: ConstantKind::Extern { def_id: assoc_item.def_id },
1306                            type_: ty,
1307                        }))
1308                    } else {
1309                        RequiredAssocConstItem(generics, Box::new(ty))
1310                    }
1311                }
1312            }
1313        }
1314        ty::AssocKind::Fn { has_self, .. } => {
1315            let mut item = inline::build_function(cx, assoc_item.def_id);
1316
1317            if has_self {
1318                let self_ty = match assoc_item.container {
1319                    ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
1320                        tcx.type_of(assoc_item.container_id(tcx)).instantiate_identity()
1321                    }
1322                    ty::AssocContainer::Trait => tcx.types.self_param,
1323                };
1324                let self_param_ty =
1325                    tcx.fn_sig(assoc_item.def_id).instantiate_identity().input(0).skip_binder();
1326                if self_param_ty == self_ty {
1327                    item.decl.inputs[0].type_ = SelfTy;
1328                } else if let ty::Ref(_, ty, _) = *self_param_ty.kind()
1329                    && ty == self_ty
1330                {
1331                    match item.decl.inputs[0].type_ {
1332                        BorrowedRef { ref mut type_, .. } => **type_ = SelfTy,
1333                        _ => unreachable!(),
1334                    }
1335                }
1336            }
1337
1338            let provided = match assoc_item.container {
1339                ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => true,
1340                ty::AssocContainer::Trait => assoc_item.defaultness(tcx).has_value(),
1341            };
1342            if provided {
1343                let defaultness = match assoc_item.container {
1344                    ty::AssocContainer::TraitImpl(_) => Some(assoc_item.defaultness(tcx)),
1345                    ty::AssocContainer::InherentImpl | ty::AssocContainer::Trait => None,
1346                };
1347                MethodItem(item, defaultness)
1348            } else {
1349                RequiredMethodItem(item)
1350            }
1351        }
1352        ty::AssocKind::Type { .. } => {
1353            let my_name = assoc_item.name();
1354
1355            fn param_eq_arg(param: &GenericParamDef, arg: &GenericArg) -> bool {
1356                match (&param.kind, arg) {
1357                    (GenericParamDefKind::Type { .. }, GenericArg::Type(Type::Generic(ty)))
1358                        if *ty == param.name =>
1359                    {
1360                        true
1361                    }
1362                    (GenericParamDefKind::Lifetime { .. }, GenericArg::Lifetime(Lifetime(lt)))
1363                        if *lt == param.name =>
1364                    {
1365                        true
1366                    }
1367                    (GenericParamDefKind::Const { .. }, GenericArg::Const(c)) => match &**c {
1368                        ConstantKind::TyConst { expr } => **expr == *param.name.as_str(),
1369                        _ => false,
1370                    },
1371                    _ => false,
1372                }
1373            }
1374
1375            let mut predicates = tcx.explicit_predicates_of(assoc_item.def_id).predicates;
1376            if let ty::AssocContainer::Trait = assoc_item.container {
1377                let bounds = tcx.explicit_item_bounds(assoc_item.def_id).iter_identity_copied();
1378                predicates = tcx.arena.alloc_from_iter(bounds.chain(predicates.iter().copied()));
1379            }
1380            let mut generics = clean_ty_generics_inner(
1381                cx,
1382                tcx.generics_of(assoc_item.def_id),
1383                ty::GenericPredicates { parent: None, predicates },
1384            );
1385            simplify::move_bounds_to_generic_parameters(&mut generics);
1386
1387            if let ty::AssocContainer::Trait = assoc_item.container {
1388                // Move bounds that are (likely) directly attached to the associated type
1389                // from the where-clause to the associated type.
1390                // There is no guarantee that this is what the user actually wrote but we have
1391                // no way of knowing.
1392                let mut bounds: Vec<GenericBound> = Vec::new();
1393                generics.where_predicates.retain_mut(|pred| match *pred {
1394                    WherePredicate::BoundPredicate {
1395                        ty:
1396                            QPath(box QPathData {
1397                                ref assoc,
1398                                ref self_type,
1399                                trait_: Some(ref trait_),
1400                                ..
1401                            }),
1402                        bounds: ref mut pred_bounds,
1403                        ..
1404                    } => {
1405                        if assoc.name != my_name {
1406                            return true;
1407                        }
1408                        if trait_.def_id() != assoc_item.container_id(tcx) {
1409                            return true;
1410                        }
1411                        if *self_type != SelfTy {
1412                            return true;
1413                        }
1414                        match &assoc.args {
1415                            GenericArgs::AngleBracketed { args, constraints } => {
1416                                if !constraints.is_empty()
1417                                    || generics
1418                                        .params
1419                                        .iter()
1420                                        .zip(args.iter())
1421                                        .any(|(param, arg)| !param_eq_arg(param, arg))
1422                                {
1423                                    return true;
1424                                }
1425                            }
1426                            GenericArgs::Parenthesized { .. } => {
1427                                // The only time this happens is if we're inside the rustdoc for Fn(),
1428                                // which only has one associated type, which is not a GAT, so whatever.
1429                            }
1430                            GenericArgs::ReturnTypeNotation => {
1431                                // Never move these.
1432                            }
1433                        }
1434                        bounds.extend(mem::take(pred_bounds));
1435                        false
1436                    }
1437                    _ => true,
1438                });
1439
1440                bounds.retain(|b| {
1441                    // FIXME(sized-hierarchy): Always skip `MetaSized` bounds so that only `?Sized`
1442                    // is shown and none of the new sizedness traits leak into documentation.
1443                    !b.is_meta_sized_bound(cx)
1444                });
1445
1446                // Our Sized/?Sized bound didn't get handled when creating the generics
1447                // because we didn't actually get our whole set of bounds until just now
1448                // (some of them may have come from the trait). If we do have a sized
1449                // bound, we remove it, and if we don't then we add the `?Sized` bound
1450                // at the end.
1451                match bounds.iter().position(|b| b.is_sized_bound(cx)) {
1452                    Some(i) => {
1453                        bounds.remove(i);
1454                    }
1455                    None => bounds.push(GenericBound::maybe_sized(cx)),
1456                }
1457
1458                if tcx.defaultness(assoc_item.def_id).has_value() {
1459                    AssocTypeItem(
1460                        Box::new(TypeAlias {
1461                            type_: clean_middle_ty(
1462                                ty::Binder::dummy(
1463                                    tcx.type_of(assoc_item.def_id).instantiate_identity(),
1464                                ),
1465                                cx,
1466                                Some(assoc_item.def_id),
1467                                None,
1468                            ),
1469                            generics,
1470                            inner_type: None,
1471                            item_type: None,
1472                        }),
1473                        bounds,
1474                    )
1475                } else {
1476                    RequiredAssocTypeItem(generics, bounds)
1477                }
1478            } else {
1479                AssocTypeItem(
1480                    Box::new(TypeAlias {
1481                        type_: clean_middle_ty(
1482                            ty::Binder::dummy(
1483                                tcx.type_of(assoc_item.def_id).instantiate_identity(),
1484                            ),
1485                            cx,
1486                            Some(assoc_item.def_id),
1487                            None,
1488                        ),
1489                        generics,
1490                        inner_type: None,
1491                        item_type: None,
1492                    }),
1493                    // Associated types inside trait or inherent impls are not allowed to have
1494                    // item bounds. Thus we don't attempt to move any bounds there.
1495                    Vec::new(),
1496                )
1497            }
1498        }
1499    };
1500
1501    Item::from_def_id_and_parts(assoc_item.def_id, Some(assoc_item.name()), kind, cx)
1502}
1503
1504fn first_non_private_clean_path<'tcx>(
1505    cx: &mut DocContext<'tcx>,
1506    path: &hir::Path<'tcx>,
1507    new_path_segments: &'tcx [hir::PathSegment<'tcx>],
1508    new_path_span: rustc_span::Span,
1509) -> Path {
1510    let new_hir_path =
1511        hir::Path { segments: new_path_segments, res: path.res, span: new_path_span };
1512    let mut new_clean_path = clean_path(&new_hir_path, cx);
1513    // In here we need to play with the path data one last time to provide it the
1514    // missing `args` and `res` of the final `Path` we get, which, since it comes
1515    // from a re-export, doesn't have the generics that were originally there, so
1516    // we add them by hand.
1517    if let Some(path_last) = path.segments.last().as_ref()
1518        && let Some(new_path_last) = new_clean_path.segments[..].last_mut()
1519        && let Some(path_last_args) = path_last.args.as_ref()
1520        && path_last.args.is_some()
1521    {
1522        assert!(new_path_last.args.is_empty());
1523        new_path_last.args = clean_generic_args(path_last_args, cx);
1524    }
1525    new_clean_path
1526}
1527
1528/// The goal of this function is to return the first `Path` which is not private (ie not private
1529/// or `doc(hidden)`). If it's not possible, it'll return the "end type".
1530///
1531/// If the path is not a re-export or is public, it'll return `None`.
1532fn first_non_private<'tcx>(
1533    cx: &mut DocContext<'tcx>,
1534    hir_id: hir::HirId,
1535    path: &hir::Path<'tcx>,
1536) -> Option<Path> {
1537    let target_def_id = path.res.opt_def_id()?;
1538    let (parent_def_id, ident) = match &path.segments {
1539        [] => return None,
1540        // Relative paths are available in the same scope as the owner.
1541        [leaf] => (cx.tcx.local_parent(hir_id.owner.def_id), leaf.ident),
1542        // So are self paths.
1543        [parent, leaf] if parent.ident.name == kw::SelfLower => {
1544            (cx.tcx.local_parent(hir_id.owner.def_id), leaf.ident)
1545        }
1546        // Crate paths are not. We start from the crate root.
1547        [parent, leaf] if matches!(parent.ident.name, kw::Crate | kw::PathRoot) => {
1548            (LOCAL_CRATE.as_def_id().as_local()?, leaf.ident)
1549        }
1550        [parent, leaf] if parent.ident.name == kw::Super => {
1551            let parent_mod = cx.tcx.parent_module(hir_id);
1552            if let Some(super_parent) = cx.tcx.opt_local_parent(parent_mod.to_local_def_id()) {
1553                (super_parent, leaf.ident)
1554            } else {
1555                // If we can't find the parent of the parent, then the parent is already the crate.
1556                (LOCAL_CRATE.as_def_id().as_local()?, leaf.ident)
1557            }
1558        }
1559        // Absolute paths are not. We start from the parent of the item.
1560        [.., parent, leaf] => (parent.res.opt_def_id()?.as_local()?, leaf.ident),
1561    };
1562    // First we try to get the `DefId` of the item.
1563    for child in
1564        cx.tcx.module_children_local(parent_def_id).iter().filter(move |c| c.ident == ident)
1565    {
1566        if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = child.res {
1567            continue;
1568        }
1569
1570        if let Some(def_id) = child.res.opt_def_id()
1571            && target_def_id == def_id
1572        {
1573            let mut last_path_res = None;
1574            'reexps: for reexp in child.reexport_chain.iter() {
1575                if let Some(use_def_id) = reexp.id()
1576                    && let Some(local_use_def_id) = use_def_id.as_local()
1577                    && let hir::Node::Item(item) = cx.tcx.hir_node_by_def_id(local_use_def_id)
1578                    && let hir::ItemKind::Use(path, hir::UseKind::Single(_)) = item.kind
1579                {
1580                    for res in path.res.present_items() {
1581                        if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = res {
1582                            continue;
1583                        }
1584                        if (cx.render_options.document_hidden ||
1585                            !cx.tcx.is_doc_hidden(use_def_id)) &&
1586                            // We never check for "cx.render_options.document_private"
1587                            // because if a re-export is not fully public, it's never
1588                            // documented.
1589                            cx.tcx.local_visibility(local_use_def_id).is_public()
1590                        {
1591                            break 'reexps;
1592                        }
1593                        last_path_res = Some((path, res));
1594                        continue 'reexps;
1595                    }
1596                }
1597            }
1598            if !child.reexport_chain.is_empty() {
1599                // So in here, we use the data we gathered from iterating the reexports. If
1600                // `last_path_res` is set, it can mean two things:
1601                //
1602                // 1. We found a public reexport.
1603                // 2. We didn't find a public reexport so it's the "end type" path.
1604                if let Some((new_path, _)) = last_path_res {
1605                    return Some(first_non_private_clean_path(
1606                        cx,
1607                        path,
1608                        new_path.segments,
1609                        new_path.span,
1610                    ));
1611                }
1612                // If `last_path_res` is `None`, it can mean two things:
1613                //
1614                // 1. The re-export is public, no need to change anything, just use the path as is.
1615                // 2. Nothing was found, so let's just return the original path.
1616                return None;
1617            }
1618        }
1619    }
1620    None
1621}
1622
1623fn clean_qpath<'tcx>(hir_ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type {
1624    let hir::Ty { hir_id, span, ref kind } = *hir_ty;
1625    let hir::TyKind::Path(qpath) = kind else { unreachable!() };
1626
1627    match qpath {
1628        hir::QPath::Resolved(None, path) => {
1629            if let Res::Def(DefKind::TyParam, did) = path.res {
1630                if let Some(new_ty) = cx.args.get(&did).and_then(|p| p.as_ty()).cloned() {
1631                    return new_ty;
1632                }
1633                if let Some(bounds) = cx.impl_trait_bounds.remove(&did.into()) {
1634                    return ImplTrait(bounds);
1635                }
1636            }
1637
1638            if let Some(expanded) = maybe_expand_private_type_alias(cx, path) {
1639                expanded
1640            } else {
1641                // First we check if it's a private re-export.
1642                let path = if let Some(path) = first_non_private(cx, hir_id, path) {
1643                    path
1644                } else {
1645                    clean_path(path, cx)
1646                };
1647                resolve_type(cx, path)
1648            }
1649        }
1650        hir::QPath::Resolved(Some(qself), p) => {
1651            // Try to normalize `<X as Y>::T` to a type
1652            let ty = lower_ty(cx.tcx, hir_ty);
1653            // `hir_to_ty` can return projection types with escaping vars for GATs, e.g. `<() as Trait>::Gat<'_>`
1654            if !ty.has_escaping_bound_vars()
1655                && let Some(normalized_value) = normalize(cx, ty::Binder::dummy(ty))
1656            {
1657                return clean_middle_ty(normalized_value, cx, None, None);
1658            }
1659
1660            let trait_segments = &p.segments[..p.segments.len() - 1];
1661            let trait_def = cx.tcx.parent(p.res.def_id());
1662            let trait_ = self::Path {
1663                res: Res::Def(DefKind::Trait, trait_def),
1664                segments: trait_segments.iter().map(|x| clean_path_segment(x, cx)).collect(),
1665            };
1666            register_res(cx, trait_.res);
1667            let self_def_id = DefId::local(qself.hir_id.owner.def_id.local_def_index);
1668            let self_type = clean_ty(qself, cx);
1669            let should_fully_qualify =
1670                should_fully_qualify_path(Some(self_def_id), &trait_, &self_type);
1671            Type::QPath(Box::new(QPathData {
1672                assoc: clean_path_segment(p.segments.last().expect("segments were empty"), cx),
1673                should_fully_qualify,
1674                self_type,
1675                trait_: Some(trait_),
1676            }))
1677        }
1678        hir::QPath::TypeRelative(qself, segment) => {
1679            let ty = lower_ty(cx.tcx, hir_ty);
1680            let self_type = clean_ty(qself, cx);
1681
1682            let (trait_, should_fully_qualify) = match ty.kind() {
1683                ty::Alias(ty::Projection, proj) => {
1684                    let res = Res::Def(DefKind::Trait, proj.trait_ref(cx.tcx).def_id);
1685                    let trait_ = clean_path(&hir::Path { span, res, segments: &[] }, cx);
1686                    register_res(cx, trait_.res);
1687                    let self_def_id = res.opt_def_id();
1688                    let should_fully_qualify =
1689                        should_fully_qualify_path(self_def_id, &trait_, &self_type);
1690
1691                    (Some(trait_), should_fully_qualify)
1692                }
1693                ty::Alias(ty::Inherent, _) => (None, false),
1694                // Rustdoc handles `ty::Error`s by turning them into `Type::Infer`s.
1695                ty::Error(_) => return Type::Infer,
1696                _ => bug!("clean: expected associated type, found `{ty:?}`"),
1697            };
1698
1699            Type::QPath(Box::new(QPathData {
1700                assoc: clean_path_segment(segment, cx),
1701                should_fully_qualify,
1702                self_type,
1703                trait_,
1704            }))
1705        }
1706        hir::QPath::LangItem(..) => bug!("clean: requiring documentation of lang item"),
1707    }
1708}
1709
1710fn maybe_expand_private_type_alias<'tcx>(
1711    cx: &mut DocContext<'tcx>,
1712    path: &hir::Path<'tcx>,
1713) -> Option<Type> {
1714    let Res::Def(DefKind::TyAlias, def_id) = path.res else { return None };
1715    // Substitute private type aliases
1716    let def_id = def_id.as_local()?;
1717    let alias = if !cx.cache.effective_visibilities.is_exported(cx.tcx, def_id.to_def_id())
1718        && !cx.current_type_aliases.contains_key(&def_id.to_def_id())
1719    {
1720        &cx.tcx.hir_expect_item(def_id).kind
1721    } else {
1722        return None;
1723    };
1724    let hir::ItemKind::TyAlias(_, generics, ty) = alias else { return None };
1725
1726    let final_seg = &path.segments.last().expect("segments were empty");
1727    let mut args = DefIdMap::default();
1728    let generic_args = final_seg.args();
1729
1730    let mut indices: hir::GenericParamCount = Default::default();
1731    for param in generics.params.iter() {
1732        match param.kind {
1733            hir::GenericParamKind::Lifetime { .. } => {
1734                let mut j = 0;
1735                let lifetime = generic_args.args.iter().find_map(|arg| match arg {
1736                    hir::GenericArg::Lifetime(lt) => {
1737                        if indices.lifetimes == j {
1738                            return Some(lt);
1739                        }
1740                        j += 1;
1741                        None
1742                    }
1743                    _ => None,
1744                });
1745                if let Some(lt) = lifetime {
1746                    let lt = if !lt.is_anonymous() {
1747                        clean_lifetime(lt, cx)
1748                    } else {
1749                        Lifetime::elided()
1750                    };
1751                    args.insert(param.def_id.to_def_id(), GenericArg::Lifetime(lt));
1752                }
1753                indices.lifetimes += 1;
1754            }
1755            hir::GenericParamKind::Type { ref default, .. } => {
1756                let mut j = 0;
1757                let type_ = generic_args.args.iter().find_map(|arg| match arg {
1758                    hir::GenericArg::Type(ty) => {
1759                        if indices.types == j {
1760                            return Some(ty.as_unambig_ty());
1761                        }
1762                        j += 1;
1763                        None
1764                    }
1765                    _ => None,
1766                });
1767                if let Some(ty) = type_.or(*default) {
1768                    args.insert(param.def_id.to_def_id(), GenericArg::Type(clean_ty(ty, cx)));
1769                }
1770                indices.types += 1;
1771            }
1772            // FIXME(#82852): Instantiate const parameters.
1773            hir::GenericParamKind::Const { .. } => {}
1774        }
1775    }
1776
1777    Some(cx.enter_alias(args, def_id.to_def_id(), |cx| {
1778        cx.with_param_env(def_id.to_def_id(), |cx| clean_ty(ty, cx))
1779    }))
1780}
1781
1782pub(crate) fn clean_ty<'tcx>(ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type {
1783    use rustc_hir::*;
1784
1785    match ty.kind {
1786        TyKind::Never => Primitive(PrimitiveType::Never),
1787        TyKind::Ptr(ref m) => RawPointer(m.mutbl, Box::new(clean_ty(m.ty, cx))),
1788        TyKind::Ref(l, ref m) => {
1789            let lifetime = if l.is_anonymous() { None } else { Some(clean_lifetime(l, cx)) };
1790            BorrowedRef { lifetime, mutability: m.mutbl, type_: Box::new(clean_ty(m.ty, cx)) }
1791        }
1792        TyKind::Slice(ty) => Slice(Box::new(clean_ty(ty, cx))),
1793        TyKind::Pat(ty, pat) => Type::Pat(Box::new(clean_ty(ty, cx)), format!("{pat:?}").into()),
1794        TyKind::Array(ty, const_arg) => {
1795            // NOTE(min_const_generics): We can't use `const_eval_poly` for constants
1796            // as we currently do not supply the parent generics to anonymous constants
1797            // but do allow `ConstKind::Param`.
1798            //
1799            // `const_eval_poly` tries to first substitute generic parameters which
1800            // results in an ICE while manually constructing the constant and using `eval`
1801            // does nothing for `ConstKind::Param`.
1802            let length = match const_arg.kind {
1803                hir::ConstArgKind::Infer(..) => "_".to_string(),
1804                hir::ConstArgKind::Anon(hir::AnonConst { def_id, .. }) => {
1805                    let ct = lower_const_arg_for_rustdoc(cx.tcx, const_arg, FeedConstTy::No);
1806                    let typing_env = ty::TypingEnv::post_analysis(cx.tcx, *def_id);
1807                    let ct = cx.tcx.normalize_erasing_regions(typing_env, ct);
1808                    print_const(cx, ct)
1809                }
1810                hir::ConstArgKind::Path(..) => {
1811                    let ct = lower_const_arg_for_rustdoc(cx.tcx, const_arg, FeedConstTy::No);
1812                    print_const(cx, ct)
1813                }
1814            };
1815            Array(Box::new(clean_ty(ty, cx)), length.into())
1816        }
1817        TyKind::Tup(tys) => Tuple(tys.iter().map(|ty| clean_ty(ty, cx)).collect()),
1818        TyKind::OpaqueDef(ty) => {
1819            ImplTrait(ty.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect())
1820        }
1821        TyKind::Path(_) => clean_qpath(ty, cx),
1822        TyKind::TraitObject(bounds, lifetime) => {
1823            let bounds = bounds.iter().map(|bound| clean_poly_trait_ref(bound, cx)).collect();
1824            let lifetime = if !lifetime.is_elided() {
1825                Some(clean_lifetime(lifetime.pointer(), cx))
1826            } else {
1827                None
1828            };
1829            DynTrait(bounds, lifetime)
1830        }
1831        TyKind::FnPtr(barefn) => BareFunction(Box::new(clean_bare_fn_ty(barefn, cx))),
1832        TyKind::UnsafeBinder(unsafe_binder_ty) => {
1833            UnsafeBinder(Box::new(clean_unsafe_binder_ty(unsafe_binder_ty, cx)))
1834        }
1835        // Rustdoc handles `TyKind::Err`s by turning them into `Type::Infer`s.
1836        TyKind::Infer(())
1837        | TyKind::Err(_)
1838        | TyKind::Typeof(..)
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(), cx)))
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.render_options.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() {
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, body_id) => ConstantItem(Box::new(Constant {
2790                generics: clean_generics(generics, cx),
2791                type_: clean_ty(ty, cx),
2792                kind: ConstantKind::Local { body: body_id, 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: tcx.impl_polarity(def_id),
2938            kind: if utils::has_doc_flag(tcx, def_id.to_def_id(), sym::fake_variadic) {
2939                ImplKind::FakeVariadic
2940            } else {
2941                ImplKind::Normal
2942            },
2943        }));
2944        Item::from_def_id_and_parts(def_id.to_def_id(), None, kind, cx)
2945    };
2946    if let Some(type_alias) = type_alias {
2947        ret.push(make_item(trait_.clone(), type_alias, items.clone()));
2948    }
2949    ret.push(make_item(trait_, for_, items));
2950    ret
2951}
2952
2953fn clean_extern_crate<'tcx>(
2954    krate: &hir::Item<'tcx>,
2955    name: Symbol,
2956    orig_name: Option<Symbol>,
2957    cx: &mut DocContext<'tcx>,
2958) -> Vec<Item> {
2959    // this is the ID of the `extern crate` statement
2960    let cnum = cx.tcx.extern_mod_stmt_cnum(krate.owner_id.def_id).unwrap_or(LOCAL_CRATE);
2961    // this is the ID of the crate itself
2962    let crate_def_id = cnum.as_def_id();
2963    let attrs = cx.tcx.hir_attrs(krate.hir_id());
2964    let ty_vis = cx.tcx.visibility(krate.owner_id);
2965    let please_inline = ty_vis.is_public()
2966        && attrs.iter().any(|a| {
2967            a.has_name(sym::doc)
2968                && match a.meta_item_list() {
2969                    Some(l) => ast::attr::list_contains_name(&l, sym::inline),
2970                    None => false,
2971                }
2972        })
2973        && !cx.is_json_output();
2974
2975    let krate_owner_def_id = krate.owner_id.def_id;
2976
2977    if please_inline
2978        && let Some(items) = inline::try_inline(
2979            cx,
2980            Res::Def(DefKind::Mod, crate_def_id),
2981            name,
2982            Some((attrs, Some(krate_owner_def_id))),
2983            &mut Default::default(),
2984        )
2985    {
2986        return items;
2987    }
2988
2989    vec![Item::from_def_id_and_parts(
2990        krate_owner_def_id.to_def_id(),
2991        Some(name),
2992        ExternCrateItem { src: orig_name },
2993        cx,
2994    )]
2995}
2996
2997fn clean_use_statement<'tcx>(
2998    import: &hir::Item<'tcx>,
2999    name: Option<Symbol>,
3000    path: &hir::UsePath<'tcx>,
3001    kind: hir::UseKind,
3002    cx: &mut DocContext<'tcx>,
3003    inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
3004) -> Vec<Item> {
3005    let mut items = Vec::new();
3006    let hir::UsePath { segments, ref res, span } = *path;
3007    for res in res.present_items() {
3008        let path = hir::Path { segments, res, span };
3009        items.append(&mut clean_use_statement_inner(import, name, &path, kind, cx, inlined_names));
3010    }
3011    items
3012}
3013
3014fn clean_use_statement_inner<'tcx>(
3015    import: &hir::Item<'tcx>,
3016    name: Option<Symbol>,
3017    path: &hir::Path<'tcx>,
3018    kind: hir::UseKind,
3019    cx: &mut DocContext<'tcx>,
3020    inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
3021) -> Vec<Item> {
3022    if should_ignore_res(path.res) {
3023        return Vec::new();
3024    }
3025    // We need this comparison because some imports (for std types for example)
3026    // are "inserted" as well but directly by the compiler and they should not be
3027    // taken into account.
3028    if import.span.ctxt().outer_expn_data().kind == ExpnKind::AstPass(AstPass::StdImports) {
3029        return Vec::new();
3030    }
3031
3032    let visibility = cx.tcx.visibility(import.owner_id);
3033    let attrs = cx.tcx.hir_attrs(import.hir_id());
3034    let inline_attr = hir_attr_lists(attrs, sym::doc).get_word_attr(sym::inline);
3035    let pub_underscore = visibility.is_public() && name == Some(kw::Underscore);
3036    let current_mod = cx.tcx.parent_module_from_def_id(import.owner_id.def_id);
3037    let import_def_id = import.owner_id.def_id;
3038
3039    // The parent of the module in which this import resides. This
3040    // is the same as `current_mod` if that's already the top
3041    // level module.
3042    let parent_mod = cx.tcx.parent_module_from_def_id(current_mod.to_local_def_id());
3043
3044    // This checks if the import can be seen from a higher level module.
3045    // In other words, it checks if the visibility is the equivalent of
3046    // `pub(super)` or higher. If the current module is the top level
3047    // module, there isn't really a parent module, which makes the results
3048    // meaningless. In this case, we make sure the answer is `false`.
3049    let is_visible_from_parent_mod =
3050        visibility.is_accessible_from(parent_mod, cx.tcx) && !current_mod.is_top_level_module();
3051
3052    if pub_underscore && let Some(ref inline) = inline_attr {
3053        struct_span_code_err!(
3054            cx.tcx.dcx(),
3055            inline.span(),
3056            E0780,
3057            "anonymous imports cannot be inlined"
3058        )
3059        .with_span_label(import.span, "anonymous import")
3060        .emit();
3061    }
3062
3063    // We consider inlining the documentation of `pub use` statements, but we
3064    // forcefully don't inline if this is not public or if the
3065    // #[doc(no_inline)] attribute is present.
3066    // Don't inline doc(hidden) imports so they can be stripped at a later stage.
3067    let mut denied = cx.is_json_output()
3068        || !(visibility.is_public()
3069            || (cx.render_options.document_private && is_visible_from_parent_mod))
3070        || pub_underscore
3071        || attrs.iter().any(|a| {
3072            a.has_name(sym::doc)
3073                && match a.meta_item_list() {
3074                    Some(l) => {
3075                        ast::attr::list_contains_name(&l, sym::no_inline)
3076                            || ast::attr::list_contains_name(&l, sym::hidden)
3077                    }
3078                    None => false,
3079                }
3080        });
3081
3082    // Also check whether imports were asked to be inlined, in case we're trying to re-export a
3083    // crate in Rust 2018+
3084    let path = clean_path(path, cx);
3085    let inner = if kind == hir::UseKind::Glob {
3086        if !denied {
3087            let mut visited = DefIdSet::default();
3088            if let Some(items) = inline::try_inline_glob(
3089                cx,
3090                path.res,
3091                current_mod,
3092                &mut visited,
3093                inlined_names,
3094                import,
3095            ) {
3096                return items;
3097            }
3098        }
3099        Import::new_glob(resolve_use_source(cx, path), true)
3100    } else {
3101        let name = name.unwrap();
3102        if inline_attr.is_none()
3103            && let Res::Def(DefKind::Mod, did) = path.res
3104            && !did.is_local()
3105            && did.is_crate_root()
3106        {
3107            // if we're `pub use`ing an extern crate root, don't inline it unless we
3108            // were specifically asked for it
3109            denied = true;
3110        }
3111        if !denied
3112            && let Some(mut items) = inline::try_inline(
3113                cx,
3114                path.res,
3115                name,
3116                Some((attrs, Some(import_def_id))),
3117                &mut Default::default(),
3118            )
3119        {
3120            items.push(Item::from_def_id_and_parts(
3121                import_def_id.to_def_id(),
3122                None,
3123                ImportItem(Import::new_simple(name, resolve_use_source(cx, path), false)),
3124                cx,
3125            ));
3126            return items;
3127        }
3128        Import::new_simple(name, resolve_use_source(cx, path), true)
3129    };
3130
3131    vec![Item::from_def_id_and_parts(import_def_id.to_def_id(), None, ImportItem(inner), cx)]
3132}
3133
3134fn clean_maybe_renamed_foreign_item<'tcx>(
3135    cx: &mut DocContext<'tcx>,
3136    item: &hir::ForeignItem<'tcx>,
3137    renamed: Option<Symbol>,
3138    import_id: Option<LocalDefId>,
3139) -> Item {
3140    let def_id = item.owner_id.to_def_id();
3141    cx.with_param_env(def_id, |cx| {
3142        let kind = match item.kind {
3143            hir::ForeignItemKind::Fn(sig, idents, generics) => ForeignFunctionItem(
3144                clean_function(cx, &sig, generics, ParamsSrc::Idents(idents)),
3145                sig.header.safety(),
3146            ),
3147            hir::ForeignItemKind::Static(ty, mutability, safety) => ForeignStaticItem(
3148                Static { type_: Box::new(clean_ty(ty, cx)), mutability, expr: None },
3149                safety,
3150            ),
3151            hir::ForeignItemKind::Type => ForeignTypeItem,
3152        };
3153
3154        generate_item_with_correct_attrs(
3155            cx,
3156            kind,
3157            item.owner_id.def_id.to_def_id(),
3158            item.ident.name,
3159            import_id.as_slice(),
3160            renamed,
3161        )
3162    })
3163}
3164
3165fn clean_assoc_item_constraint<'tcx>(
3166    constraint: &hir::AssocItemConstraint<'tcx>,
3167    cx: &mut DocContext<'tcx>,
3168) -> AssocItemConstraint {
3169    AssocItemConstraint {
3170        assoc: PathSegment {
3171            name: constraint.ident.name,
3172            args: clean_generic_args(constraint.gen_args, cx),
3173        },
3174        kind: match constraint.kind {
3175            hir::AssocItemConstraintKind::Equality { ref term } => {
3176                AssocItemConstraintKind::Equality { term: clean_hir_term(term, cx) }
3177            }
3178            hir::AssocItemConstraintKind::Bound { bounds } => AssocItemConstraintKind::Bound {
3179                bounds: bounds.iter().filter_map(|b| clean_generic_bound(b, cx)).collect(),
3180            },
3181        },
3182    }
3183}
3184
3185fn clean_bound_vars<'tcx>(
3186    bound_vars: &ty::List<ty::BoundVariableKind>,
3187    cx: &mut DocContext<'tcx>,
3188) -> Vec<GenericParamDef> {
3189    bound_vars
3190        .into_iter()
3191        .filter_map(|var| match var {
3192            ty::BoundVariableKind::Region(ty::BoundRegionKind::Named(def_id)) => {
3193                let name = cx.tcx.item_name(def_id);
3194                if name != kw::UnderscoreLifetime {
3195                    Some(GenericParamDef::lifetime(def_id, name))
3196                } else {
3197                    None
3198                }
3199            }
3200            ty::BoundVariableKind::Ty(ty::BoundTyKind::Param(def_id)) => {
3201                let name = cx.tcx.item_name(def_id);
3202                Some(GenericParamDef {
3203                    name,
3204                    def_id,
3205                    kind: GenericParamDefKind::Type {
3206                        bounds: ThinVec::new(),
3207                        default: None,
3208                        synthetic: false,
3209                    },
3210                })
3211            }
3212            // FIXME(non_lifetime_binders): Support higher-ranked const parameters.
3213            ty::BoundVariableKind::Const => None,
3214            _ => None,
3215        })
3216        .collect()
3217}