rustdoc/clean/
mod.rs

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