mod.rs - source (original) (raw)

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