Skip to main content

rustdoc/clean/
inline.rs

1//! Support for inlining external documentation into the current AST.
2
3use std::iter::once;
4use std::sync::Arc;
5
6use rustc_data_structures::fx::FxHashSet;
7use rustc_data_structures::thin_vec::{ThinVec, thin_vec};
8use rustc_hir::def::{DefKind, MacroKinds, Res};
9use rustc_hir::def_id::{DefId, DefIdSet, LocalDefId, LocalModId};
10use rustc_hir::{self as hir, HirId, Mutability, find_attr};
11use rustc_metadata::creader::{CStore, LoadedMacro};
12use rustc_middle::ty::fast_reject::SimplifiedType;
13use rustc_middle::ty::{self, TyCtxt};
14use rustc_span::def_id::LOCAL_CRATE;
15use rustc_span::hygiene::MacroKind;
16use rustc_span::symbol::{Symbol, sym};
17use tracing::{debug, instrument, trace};
18
19use super::{Item, extract_cfg_from_attrs};
20use crate::clean::{
21    self, Attributes, CfgInfo, ImplKind, ItemId, Type, clean_bound_vars, clean_generics,
22    clean_impl_item, clean_middle_assoc_item, clean_middle_field, clean_middle_ty,
23    clean_poly_fn_sig, clean_trait_ref_with_constraints, clean_ty, clean_ty_alias_inner_type,
24    clean_ty_generics, clean_variant_def, utils,
25};
26use crate::core::DocContext;
27use crate::formats::item_type::ItemType;
28
29/// Attempt to inline a definition into this AST.
30///
31/// This function will fetch the definition specified, and if it is
32/// from another crate it will attempt to inline the documentation
33/// from the other crate into this crate.
34///
35/// This is primarily used for `pub use` statements which are, in general,
36/// implementation details. Inlining the documentation should help provide a
37/// better experience when reading the documentation in this use case.
38///
39/// The returned value is `None` if the definition could not be inlined,
40/// and `Some` of a vector of items if it was successfully expanded.
41pub(crate) fn try_inline(
42    cx: &mut DocContext<'_>,
43    res: Res,
44    name: Symbol,
45    attrs: Option<(&[hir::Attribute], Option<LocalDefId>)>,
46    visited: &mut DefIdSet,
47) -> Option<Vec<clean::Item>> {
48    fn try_inline_inner(
49        cx: &mut DocContext<'_>,
50        kind: clean::ItemKind,
51        did: DefId,
52        name: Symbol,
53        import_def_id: Option<LocalDefId>,
54    ) -> clean::Item {
55        cx.inlined.insert(did.into());
56        let mut item = crate::clean::generate_item_with_correct_attrs(
57            cx,
58            kind,
59            did,
60            name,
61            import_def_id.as_slice(),
62            None,
63        );
64        // The visibility needs to reflect the one from the reexport and not from the "source" DefId.
65        item.inner.inline_stmt_id = import_def_id;
66        item
67    }
68
69    let did = res.opt_def_id()?;
70    if did.is_local() {
71        return None;
72    }
73    let mut ret = Vec::new();
74
75    debug!("attrs={attrs:?}");
76
77    let attrs_without_docs = attrs.map(|(attrs, def_id)| {
78        (attrs.iter().filter(|a| a.doc_str().is_none()).cloned().collect::<Vec<_>>(), def_id)
79    });
80    let attrs_without_docs =
81        attrs_without_docs.as_ref().map(|(attrs, def_id)| (&attrs[..], *def_id));
82
83    let import_def_id = attrs.and_then(|(_, def_id)| def_id);
84
85    let kind = match res {
86        Res::Def(DefKind::Trait, did) => {
87            record_extern_fqn(cx, did, ItemType::Trait);
88            cx.with_param_env(did, |cx| {
89                build_impls(cx, did, attrs_without_docs, &mut ret);
90                clean::TraitItem(Box::new(build_trait(cx, did)))
91            })
92        }
93        Res::Def(DefKind::TraitAlias, did) => {
94            record_extern_fqn(cx, did, ItemType::TraitAlias);
95            cx.with_param_env(did, |cx| clean::TraitAliasItem(build_trait_alias(cx, did)))
96        }
97        Res::Def(DefKind::Fn, did) => {
98            record_extern_fqn(cx, did, ItemType::Function);
99            cx.with_param_env(did, |cx| {
100                clean::enter_impl_trait(cx, |cx| clean::FunctionItem(build_function(cx, did)))
101            })
102        }
103        Res::Def(DefKind::Struct, did) => {
104            record_extern_fqn(cx, did, ItemType::Struct);
105            cx.with_param_env(did, |cx| {
106                build_impls(cx, did, attrs_without_docs, &mut ret);
107                clean::StructItem(build_struct(cx, did))
108            })
109        }
110        Res::Def(DefKind::Union, did) => {
111            record_extern_fqn(cx, did, ItemType::Union);
112            cx.with_param_env(did, |cx| {
113                build_impls(cx, did, attrs_without_docs, &mut ret);
114                clean::UnionItem(build_union(cx, did))
115            })
116        }
117        Res::Def(DefKind::TyAlias, did) => {
118            record_extern_fqn(cx, did, ItemType::TypeAlias);
119            cx.with_param_env(did, |cx| {
120                build_impls(cx, did, attrs_without_docs, &mut ret);
121                clean::TypeAliasItem(build_type_alias(cx, did, &mut ret))
122            })
123        }
124        Res::Def(DefKind::Enum, did) => {
125            record_extern_fqn(cx, did, ItemType::Enum);
126            cx.with_param_env(did, |cx| {
127                build_impls(cx, did, attrs_without_docs, &mut ret);
128                clean::EnumItem(build_enum(cx, did))
129            })
130        }
131        Res::Def(DefKind::ForeignTy, did) => {
132            record_extern_fqn(cx, did, ItemType::ForeignType);
133            cx.with_param_env(did, |cx| {
134                build_impls(cx, did, attrs_without_docs, &mut ret);
135                clean::ForeignTypeItem
136            })
137        }
138        // Never inline enum variants but leave them shown as re-exports.
139        Res::Def(DefKind::Variant, _) => return None,
140        // Assume that enum variants and struct types are re-exported next to
141        // their constructors.
142        Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) => return Some(Vec::new()),
143        Res::Def(DefKind::Mod, did) => {
144            record_extern_fqn(cx, did, ItemType::Module);
145            clean::ModuleItem(build_module(cx, did, name, visited))
146        }
147        Res::Def(DefKind::Static { .. }, did) => {
148            record_extern_fqn(cx, did, ItemType::Static);
149            cx.with_param_env(did, |cx| {
150                clean::StaticItem(build_static(cx, did, cx.tcx.is_mutable_static(did)))
151            })
152        }
153        Res::Def(DefKind::Const, did) => {
154            record_extern_fqn(cx, did, ItemType::Constant);
155            cx.with_param_env(did, |cx| {
156                let ct = build_const_item(cx, did);
157                clean::ConstantItem(Box::new(ct))
158            })
159        }
160        Res::Def(DefKind::Macro(kinds), did) => {
161            let mac = build_macro(cx.tcx, did, name, kinds);
162
163            let type_kind = match kinds {
164                MacroKinds::BANG => ItemType::Macro,
165                MacroKinds::ATTR => ItemType::ProcAttribute,
166                MacroKinds::DERIVE => ItemType::ProcDerive,
167                // Then it means it's more than one type so we default to "macro".
168                _ => ItemType::Macro,
169            };
170            record_extern_fqn(cx, did, type_kind);
171            ret.push(try_inline_inner(cx, mac, did, name, import_def_id));
172            return Some(ret);
173        }
174        _ => return None,
175    };
176
177    ret.push(try_inline_inner(cx, kind, did, name, import_def_id));
178    Some(ret)
179}
180
181pub(crate) fn try_inline_glob(
182    cx: &mut DocContext<'_>,
183    res: Res,
184    current_mod: LocalModId,
185    visited: &mut DefIdSet,
186    inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
187    import_id: LocalDefId,
188    import_hir_id: HirId,
189) -> Option<Vec<clean::Item>> {
190    let did = res.opt_def_id()?;
191    if did.is_local() {
192        return None;
193    }
194
195    match res {
196        Res::Def(DefKind::Mod, did) => {
197            // Use the set of module reexports to filter away names that are not actually
198            // reexported by the glob, e.g. because they are shadowed by something else.
199            let reexports = cx
200                .tcx
201                .module_children_local(current_mod.to_local_def_id())
202                .iter()
203                .filter(|child| !child.reexport_chain.is_empty())
204                .filter_map(|child| child.res.opt_def_id())
205                .filter(|&def_id| !cx.tcx.is_doc_hidden(def_id))
206                .collect();
207            let attrs = cx.tcx.hir_attrs(import_hir_id);
208            let mut items = build_module_items(
209                cx,
210                did,
211                cx.tcx.item_name(did),
212                visited,
213                inlined_names,
214                Some(&reexports),
215                Some((attrs, Some(import_id))),
216            );
217            items.retain(|item| {
218                if let Some(name) = item.name {
219                    // If an item with the same type and name already exists,
220                    // it takes priority over the inlined stuff.
221                    inlined_names.insert((item.type_(), name))
222                } else {
223                    true
224                }
225            });
226            Some(items)
227        }
228        // glob imports on things like enums aren't inlined even for local exports, so just bail
229        _ => None,
230    }
231}
232
233pub(crate) fn load_attrs<'hir>(tcx: TyCtxt<'hir>, did: DefId) -> &'hir [hir::Attribute] {
234    // FIXME: all uses should use `find_attr`!
235    #[allow(deprecated)]
236    tcx.get_all_attrs(did)
237}
238
239pub(crate) fn item_relative_path(tcx: TyCtxt<'_>, def_id: DefId) -> Vec<Symbol> {
240    tcx.def_path(def_id).data.into_iter().filter_map(|elem| elem.data.get_opt_name()).collect()
241}
242
243/// Get the public Rust path to an item. This is used to generate the URL to the item's page.
244///
245/// In particular: we handle macro differently: if it's not a macro 2.0 oe a built-in macro, then
246/// it is generated at the top-level of the crate and its path will be `[crate_name, macro_name]`.
247pub(crate) fn get_item_path(tcx: TyCtxt<'_>, def_id: DefId, kind: ItemType) -> Vec<Symbol> {
248    let crate_name = tcx.crate_name(def_id.krate);
249    let relative = item_relative_path(tcx, def_id);
250
251    if let ItemType::Macro = kind {
252        // Check to see if it is a macro 2.0 or built-in macro
253        // More information in <https://rust-lang.github.io/rfcs/1584-macros.html>.
254        let is_macro_2_0_or_builtin = if let Some(local_def_id) = def_id.as_local() {
255            let (_, macro_def, _) = tcx.hir_expect_item(local_def_id).expect_macro();
256            !macro_def.macro_rules
257        } else {
258            matches!(
259                CStore::from_tcx(tcx).load_macro_untracked(tcx, def_id),
260                LoadedMacro::MacroDef { def, .. } if !def.macro_rules
261            )
262        };
263        if !is_macro_2_0_or_builtin {
264            return vec![crate_name, *relative.last().expect("relative was empty")];
265        }
266    }
267
268    once(crate_name).chain(relative).collect()
269}
270
271/// Record an external fully qualified name in the external_paths cache.
272///
273/// These names are used later on by HTML rendering to generate things like
274/// source links back to the original item.
275pub(crate) fn record_extern_fqn(cx: &mut DocContext<'_>, did: DefId, kind: ItemType) {
276    if did.is_local() {
277        if cx.cache.exact_paths.contains_key(&did) {
278            return;
279        }
280    } else if cx.cache.external_paths.contains_key(&did) {
281        return;
282    }
283
284    let item_path = get_item_path(cx.tcx, did, kind);
285
286    if did.is_local() {
287        cx.cache.exact_paths.insert(did, item_path);
288    } else {
289        cx.cache.external_paths.insert(did, (item_path, kind));
290    }
291}
292
293pub(crate) fn build_trait(cx: &mut DocContext<'_>, did: DefId) -> clean::Trait {
294    let trait_items = cx
295        .tcx
296        .associated_items(did)
297        .in_definition_order()
298        .filter(|item| !item.is_impl_trait_in_trait())
299        .map(|item| clean_middle_assoc_item(item, cx))
300        .collect();
301
302    let generics = clean_ty_generics(cx, did);
303    let (generics, mut supertrait_bounds) = separate_self_bounds(generics);
304
305    supertrait_bounds.retain(|b| {
306        // FIXME(sized-hierarchy): Always skip `MetaSized` bounds so that only `?Sized`
307        // is shown and none of the new sizedness traits leak into documentation.
308        !b.is_meta_sized_bound(cx.tcx)
309    });
310
311    clean::Trait { def_id: did, generics, items: trait_items, bounds: supertrait_bounds }
312}
313
314fn build_trait_alias(cx: &mut DocContext<'_>, did: DefId) -> clean::TraitAlias {
315    let generics = clean_ty_generics(cx, did);
316    let (generics, mut bounds) = separate_self_bounds(generics);
317
318    bounds.retain(|b| {
319        // FIXME(sized-hierarchy): Always skip `MetaSized` bounds so that only `?Sized`
320        // is shown and none of the new sizedness traits leak into documentation.
321        !b.is_meta_sized_bound(cx.tcx)
322    });
323
324    clean::TraitAlias { generics, bounds }
325}
326
327pub(super) fn build_function(cx: &mut DocContext<'_>, def_id: DefId) -> Box<clean::Function> {
328    let sig = cx.tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
329    // The generics need to be cleaned before the signature.
330    let mut generics = clean_ty_generics(cx, def_id);
331    let bound_vars = clean_bound_vars(sig.bound_vars(), cx.tcx);
332
333    // At the time of writing early & late-bound params are stored separately in rustc,
334    // namely in `generics.params` and `bound_vars` respectively.
335    //
336    // To reestablish the original source code order of the generic parameters, we
337    // need to manually sort them by their definition span after concatenation.
338    //
339    // See also:
340    // * https://rustc-dev-guide.rust-lang.org/bound-vars-and-params.html
341    // * https://rustc-dev-guide.rust-lang.org/what-does-early-late-bound-mean.html
342    let has_early_bound_params = !generics.params.is_empty();
343    let has_late_bound_params = !bound_vars.is_empty();
344    generics.params.extend(bound_vars);
345    if has_early_bound_params && has_late_bound_params {
346        // If this ever becomes a performances bottleneck either due to the sorting
347        // or due to the query calls, consider inserting the late-bound lifetime params
348        // right after the last early-bound lifetime param followed by only sorting
349        // the slice of lifetime params.
350        generics.params.sort_by_key(|param| cx.tcx.def_ident_span(param.def_id).unwrap());
351    }
352
353    let decl = clean_poly_fn_sig(cx, Some(def_id), sig);
354
355    Box::new(clean::Function { decl, generics })
356}
357
358fn build_enum(cx: &mut DocContext<'_>, did: DefId) -> clean::Enum {
359    clean::Enum {
360        generics: clean_ty_generics(cx, did),
361        variants: cx.tcx.adt_def(did).variants().iter().map(|v| clean_variant_def(v, cx)).collect(),
362    }
363}
364
365fn build_struct(cx: &mut DocContext<'_>, did: DefId) -> clean::Struct {
366    let variant = cx.tcx.adt_def(did).non_enum_variant();
367
368    clean::Struct {
369        ctor_kind: variant.ctor_kind(),
370        generics: clean_ty_generics(cx, did),
371        fields: variant.fields.iter().map(|x| clean_middle_field(x, cx)).collect(),
372    }
373}
374
375fn build_union(cx: &mut DocContext<'_>, did: DefId) -> clean::Union {
376    let variant = cx.tcx.adt_def(did).non_enum_variant();
377
378    let generics = clean_ty_generics(cx, did);
379    let fields = variant.fields.iter().map(|x| clean_middle_field(x, cx)).collect();
380    clean::Union { generics, fields }
381}
382
383fn build_type_alias(
384    cx: &mut DocContext<'_>,
385    did: DefId,
386    ret: &mut Vec<Item>,
387) -> Box<clean::TypeAlias> {
388    let ty = cx.tcx.type_of(did).instantiate_identity().skip_norm_wip();
389    let type_ = clean_middle_ty(ty::Binder::dummy(ty), cx, Some(did), None);
390    let inner_type = clean_ty_alias_inner_type(ty, cx, ret);
391
392    Box::new(clean::TypeAlias {
393        type_,
394        generics: clean_ty_generics(cx, did),
395        inner_type,
396        item_type: None,
397    })
398}
399
400/// Builds all inherent implementations of an ADT (struct/union/enum) or Trait item/path/reexport.
401pub(crate) fn build_impls(
402    cx: &mut DocContext<'_>,
403    did: DefId,
404    attrs: Option<(&[hir::Attribute], Option<LocalDefId>)>,
405    ret: &mut Vec<clean::Item>,
406) {
407    let tcx = cx.tcx;
408    let _prof_timer = tcx.sess.prof.generic_activity("build_inherent_impls");
409
410    // for each implementation of an item represented by `did`, build the clean::Item for that impl
411    for &did in tcx.inherent_impls(did).iter() {
412        cx.with_param_env(did, |cx| {
413            build_impl(cx, did, attrs, ret);
414        });
415    }
416
417    // This pretty much exists expressly for `dyn Error` traits that exist in the `alloc` crate.
418    // See also:
419    //
420    // * https://github.com/rust-lang/rust/issues/103170 — where it didn't used to get documented
421    // * https://github.com/rust-lang/rust/pull/99917 — where the feature got used
422    // * https://github.com/rust-lang/rust/issues/53487 — overall tracking issue for Error
423    if find_attr!(tcx, did, RustcHasIncoherentInherentImpls) {
424        let type_ =
425            if tcx.is_trait(did) { SimplifiedType::Trait(did) } else { SimplifiedType::Adt(did) };
426        for &did in tcx.incoherent_impls(type_).iter() {
427            cx.with_param_env(did, |cx| {
428                build_impl(cx, did, attrs, ret);
429            });
430        }
431    }
432}
433
434pub(crate) fn merge_attrs(
435    tcx: TyCtxt<'_>,
436    old_attrs: &[hir::Attribute],
437    new_attrs: Option<(&[hir::Attribute], Option<LocalDefId>)>,
438    cfg_info: &mut CfgInfo,
439) -> (clean::Attributes, Option<Arc<clean::cfg::Cfg>>) {
440    // NOTE: If we have additional attributes (from a re-export),
441    // always insert them first. This ensure that re-export
442    // doc comments show up before the original doc comments
443    // when we render them.
444    if let Some((inner, item_id)) = new_attrs {
445        let mut both = inner.to_vec();
446        both.extend_from_slice(old_attrs);
447        (
448            if let Some(item_id) = item_id {
449                Attributes::from_hir_with_additional(old_attrs, (inner, item_id.to_def_id()))
450            } else {
451                Attributes::from_hir(&both)
452            },
453            extract_cfg_from_attrs(both.iter(), tcx, cfg_info),
454        )
455    } else {
456        (Attributes::from_hir(old_attrs), extract_cfg_from_attrs(old_attrs.iter(), tcx, cfg_info))
457    }
458}
459
460/// Inline an `impl`, inherent or of a trait. The `did` must be for an `impl`.
461#[instrument(level = "debug", skip(cx, ret))]
462pub(crate) fn build_impl(
463    cx: &mut DocContext<'_>,
464    did: DefId,
465    attrs: Option<(&[hir::Attribute], Option<LocalDefId>)>,
466    ret: &mut Vec<clean::Item>,
467) {
468    if !cx.inlined.insert(did.into()) {
469        return;
470    }
471
472    let tcx = cx.tcx;
473    let _prof_timer = tcx.sess.prof.generic_activity("build_impl");
474
475    let associated_trait = tcx.impl_opt_trait_ref(did).map(ty::EarlyBinder::skip_binder);
476
477    // Do not inline compiler-internal items unless we're a compiler-internal crate.
478    let is_compiler_internal = |did| {
479        tcx.lookup_stability(did)
480            .is_some_and(|stab| stab.is_unstable() && stab.feature == sym::rustc_private)
481    };
482    let document_compiler_internal = is_compiler_internal(LOCAL_CRATE.as_def_id());
483    let is_directly_public = |cx: &mut DocContext<'_>, did| {
484        cx.cache.effective_visibilities.is_directly_public(tcx, did)
485            && (document_compiler_internal || !is_compiler_internal(did))
486    };
487
488    // Only inline impl if the implemented trait is
489    // reachable in rustdoc generated documentation
490    if !did.is_local()
491        && let Some(traitref) = associated_trait
492        && !is_directly_public(cx, traitref.def_id)
493    {
494        return;
495    }
496
497    let impl_item = match did.as_local() {
498        Some(did) => match &tcx.hir_expect_item(did).kind {
499            hir::ItemKind::Impl(impl_) => Some(impl_),
500            _ => panic!("`DefID` passed to `build_impl` is not an `impl"),
501        },
502        None => None,
503    };
504
505    let for_ = match &impl_item {
506        Some(impl_) => clean_ty(impl_.self_ty, cx),
507        None => clean_middle_ty(
508            ty::Binder::dummy(tcx.type_of(did).instantiate_identity().skip_norm_wip()),
509            cx,
510            Some(did),
511            None,
512        ),
513    };
514
515    // Only inline impl if the implementing type is
516    // reachable in rustdoc generated documentation
517    if !did.is_local()
518        && let Some(did) = for_.def_id(&cx.cache)
519        && !is_directly_public(cx, did)
520    {
521        return;
522    }
523
524    let document_hidden = cx.document_hidden();
525    let (trait_items, generics) = match impl_item {
526        Some(impl_) => (
527            impl_
528                .items
529                .iter()
530                .map(|&item| tcx.hir_impl_item(item))
531                .filter(|item| {
532                    // Filter out impl items whose corresponding trait item has `doc(hidden)`
533                    // not to document such impl items.
534                    // For inherent impls, we don't do any filtering, because that's already done in strip_hidden.rs.
535
536                    // When `--document-hidden-items` is passed, we don't
537                    // do any filtering, too.
538                    if document_hidden {
539                        return true;
540                    }
541                    if let Some(associated_trait) = associated_trait {
542                        let assoc_tag = match item.kind {
543                            hir::ImplItemKind::Const(..) => ty::AssocTag::Const,
544                            hir::ImplItemKind::Fn(..) => ty::AssocTag::Fn,
545                            hir::ImplItemKind::Type(..) => ty::AssocTag::Type,
546                        };
547                        let trait_item = tcx
548                            .associated_items(associated_trait.def_id)
549                            .find_by_ident_and_kind(
550                                tcx,
551                                item.ident,
552                                assoc_tag,
553                                associated_trait.def_id,
554                            )
555                            .unwrap(); // SAFETY: For all impl items there exists trait item that has the same name.
556                        !tcx.is_doc_hidden(trait_item.def_id)
557                    } else {
558                        true
559                    }
560                })
561                .map(|item| clean_impl_item(item, cx))
562                .collect::<Vec<_>>(),
563            clean_generics(impl_.generics, cx),
564        ),
565        None => (
566            tcx.associated_items(did)
567                .in_definition_order()
568                .filter(|item| !item.is_impl_trait_in_trait())
569                .filter(|item| {
570                    // If this is a trait impl, filter out associated items whose corresponding item
571                    // in the associated trait is marked `doc(hidden)`.
572                    // If this is an inherent impl, filter out private associated items.
573                    if let Some(associated_trait) = associated_trait {
574                        let trait_item = tcx
575                            .associated_items(associated_trait.def_id)
576                            .find_by_ident_and_kind(
577                                tcx,
578                                item.ident(tcx),
579                                item.tag(),
580                                associated_trait.def_id,
581                            )
582                            .unwrap(); // corresponding associated item has to exist
583                        document_hidden || !tcx.is_doc_hidden(trait_item.def_id)
584                    } else {
585                        item.visibility(tcx).is_public()
586                    }
587                })
588                .map(|item| clean_middle_assoc_item(item, cx))
589                .collect::<Vec<_>>(),
590            clean::enter_impl_trait(cx, |cx| clean_ty_generics(cx, did)),
591        ),
592    };
593    let polarity = if associated_trait.is_some() {
594        tcx.impl_polarity(did)
595    } else {
596        ty::ImplPolarity::Positive
597    };
598    let trait_ = associated_trait
599        .map(|t| clean_trait_ref_with_constraints(cx, ty::Binder::dummy(t), ThinVec::new()));
600    if trait_.as_ref().map(|t| t.def_id()) == tcx.lang_items().deref_trait()
601        && polarity != ty::ImplPolarity::Negative
602    {
603        super::build_deref_target_impls(cx, &trait_items, ret);
604    }
605
606    if !document_hidden {
607        // Return if the trait itself or any types of the generic parameters are doc(hidden).
608        let mut stack: Vec<&Type> = vec![&for_];
609
610        if let Some(did) = trait_.as_ref().map(|t| t.def_id())
611            && tcx.is_doc_hidden(did)
612        {
613            return;
614        }
615
616        if let Some(generics) = trait_.as_ref().and_then(|t| t.generics()) {
617            stack.extend(generics);
618        }
619
620        while let Some(ty) = stack.pop() {
621            if let Some(did) = ty.def_id(&cx.cache)
622                && tcx.is_doc_hidden(did)
623            {
624                return;
625            }
626            if let Some(generics) = ty.generics() {
627                stack.extend(generics);
628            }
629        }
630    }
631
632    if let Some(did) = trait_.as_ref().map(|t| t.def_id()) {
633        cx.with_param_env(did, |cx| {
634            record_extern_trait(cx, did);
635        });
636    }
637
638    // In here, we pass an empty `CfgInfo` because the computation of `cfg` happens later, so it
639    // doesn't matter at this point.
640    //
641    // We need to pass this empty `CfgInfo` because `merge_attrs` is used when computing the `cfg`.
642    let (merged_attrs, cfg) =
643        merge_attrs(cx.tcx, load_attrs(cx.tcx, did), attrs, &mut CfgInfo::default());
644    trace!("merged_attrs={merged_attrs:?}");
645
646    trace!(
647        "build_impl: impl {:?} for {:?}",
648        trait_.as_ref().map(|t| t.def_id()),
649        for_.def_id(&cx.cache)
650    );
651    ret.push(clean::Item::from_def_id_and_attrs_and_parts(
652        did,
653        None,
654        clean::ImplItem(Box::new(clean::Impl {
655            safety: hir::Safety::Safe,
656            generics,
657            trait_,
658            for_,
659            items: trait_items,
660            polarity,
661            kind: if utils::has_doc_flag(tcx, did, |d| d.fake_variadic.is_some()) {
662                ImplKind::FakeVariadic
663            } else {
664                ImplKind::Normal
665            },
666            is_deprecated: tcx
667                .lookup_deprecation(did)
668                .is_some_and(|deprecation| deprecation.is_in_effect()),
669        })),
670        merged_attrs,
671        cfg,
672    ));
673}
674
675fn build_module(
676    cx: &mut DocContext<'_>,
677    did: DefId,
678    name: Symbol,
679    visited: &mut DefIdSet,
680) -> clean::Module {
681    let items = build_module_items(cx, did, name, visited, &mut FxHashSet::default(), None, None);
682
683    let span = clean::Span::new(cx.tcx.def_span(did));
684    clean::Module { items, span }
685}
686
687// We are only interested into `Res::Def`. And in there, we only want "items" which get their own
688//  rustdoc page. So not `DefKind::Ctor` for example (which is returned by `tcx.module_children()`).
689fn should_ignore_res(res: Res) -> bool {
690    !matches!(res, Res::Def(def_kind, _) if !should_ignore_def_kind(def_kind))
691}
692
693fn should_ignore_def_kind(kind: DefKind) -> bool {
694    !matches!(
695        kind,
696        DefKind::Trait
697            | DefKind::TraitAlias
698            | DefKind::Fn
699            | DefKind::Struct
700            | DefKind::Union
701            | DefKind::TyAlias
702            | DefKind::Enum
703            | DefKind::ForeignTy
704            | DefKind::Variant
705            | DefKind::Mod
706            | DefKind::Static { .. }
707            | DefKind::Const
708            | DefKind::Macro(_)
709            | DefKind::Use
710    )
711}
712
713fn build_module_items(
714    cx: &mut DocContext<'_>,
715    module_def_id: DefId,
716    module_name: Symbol,
717    visited: &mut DefIdSet,
718    inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
719    allowed_def_ids: Option<&DefIdSet>,
720    attrs: Option<(&[hir::Attribute], Option<LocalDefId>)>,
721) -> Vec<clean::Item> {
722    let mut items = Vec::new();
723
724    // If we're re-exporting a re-export it may actually re-export something in
725    // two namespaces, so the target may be listed twice. Make sure we only
726    // visit each node at most once.
727    for item in cx.tcx.module_children(module_def_id).iter() {
728        if !item.vis.is_public() {
729            continue;
730        }
731        let res = item.res.expect_non_local();
732        if let Some(def_id) = res.opt_def_id()
733            && let Some(allowed_def_ids) = allowed_def_ids
734            && !allowed_def_ids.contains(&def_id)
735        {
736            continue;
737        }
738        if let Some(def_id) = res.mod_def_id() {
739            // If we're inlining a glob import, it's possible to have
740            // two distinct modules with the same name. We don't want to
741            // inline it, or mark any of its contents as visited.
742            if module_def_id == def_id
743                || inlined_names.contains(&(ItemType::Module, item.ident.name))
744                || !visited.insert(def_id)
745            {
746                continue;
747            }
748        }
749        if let Res::PrimTy(p) = res {
750            // Primitive types can't be inlined so generate an import instead.
751            let prim_ty = clean::PrimitiveType::from(p);
752            items.push(clean::Item {
753                inner: Box::new(clean::ItemInner {
754                    name: None,
755                    // We can use the item's `DefId` directly since the only information ever
756                    // used from it is `DefId.krate`.
757                    item_id: ItemId::DefId(module_def_id),
758                    attrs: Default::default(),
759                    stability: None,
760                    kind: clean::ImportItem(clean::Import::new_simple(
761                        item.ident.name,
762                        clean::ImportSource {
763                            path: clean::Path {
764                                res,
765                                segments: thin_vec![clean::PathSegment {
766                                    name: prim_ty.as_sym(),
767                                    args: clean::GenericArgs::AngleBracketed {
768                                        args: Default::default(),
769                                        constraints: ThinVec::new(),
770                                    },
771                                }],
772                            },
773                            did: None,
774                        },
775                        true,
776                    )),
777                    cfg: None,
778                    inline_stmt_id: None,
779                }),
780            });
781        } else if let Some(def_id) = res.opt_def_id()
782            && let Some(reexport) = item.reexport_chain.first()
783            && let Some(reexport_def_id) = reexport.id()
784            && !should_ignore_def_kind(cx.tcx.def_kind(reexport_def_id))
785            && find_attr!(
786                load_attrs(cx.tcx, reexport_def_id),
787                Doc(d)
788                if d.inline.first().is_some_and(|(inline, _)| *inline == hir::attrs::DocInline::NoInline)
789            )
790        {
791            // We don't inline foreign `use`.
792            if should_ignore_res(res) || matches!(res, Res::Def(DefKind::Use, _)) {
793                continue;
794            }
795            // This item is reexported as `no_inline` so it shouldn't be inlined.
796            let item = Item::from_def_id_and_parts(
797                module_def_id,
798                None,
799                clean::ImportItem(clean::Import::new_simple(
800                    item.ident.name,
801                    clean::ImportSource {
802                        path: clean::Path {
803                            res,
804                            segments: thin_vec![
805                                clean::PathSegment {
806                                    name: module_name,
807                                    args: clean::GenericArgs::AngleBracketed {
808                                        args: Default::default(),
809                                        constraints: ThinVec::new(),
810                                    },
811                                },
812                                clean::PathSegment {
813                                    name: cx.tcx.item_name(def_id),
814                                    args: clean::GenericArgs::AngleBracketed {
815                                        args: Default::default(),
816                                        constraints: ThinVec::new(),
817                                    },
818                                },
819                            ],
820                        },
821                        did: None,
822                    },
823                    true,
824                )),
825                cx.tcx,
826            );
827            items.push(item);
828        } else if let Some(i) = try_inline(cx, res, item.ident.name, attrs, visited) {
829            items.extend(i)
830        }
831    }
832
833    items
834}
835
836pub(crate) fn print_inlined_const(tcx: TyCtxt<'_>, did: DefId) -> String {
837    if let Some(did) = did.as_local() {
838        let hir_id = tcx.local_def_id_to_hir_id(did);
839        rustc_hir_pretty::id_to_string(&tcx, hir_id)
840    } else {
841        tcx.rendered_const(did).clone()
842    }
843}
844
845fn build_const_item(cx: &mut DocContext<'_>, def_id: DefId) -> clean::Constant {
846    let mut generics = clean_ty_generics(cx, def_id);
847    clean::simplify::move_bounds_to_generic_parameters(&mut generics);
848    let ty = clean_middle_ty(
849        ty::Binder::dummy(cx.tcx.type_of(def_id).instantiate_identity().skip_norm_wip()),
850        cx,
851        None,
852        None,
853    );
854    clean::Constant { generics, type_: ty, kind: clean::ConstantKind::Extern { def_id } }
855}
856
857fn build_static(cx: &mut DocContext<'_>, did: DefId, mutable: bool) -> clean::Static {
858    clean::Static {
859        type_: Box::new(clean_middle_ty(
860            ty::Binder::dummy(cx.tcx.type_of(did).instantiate_identity().skip_norm_wip()),
861            cx,
862            Some(did),
863            None,
864        )),
865        mutability: if mutable { Mutability::Mut } else { Mutability::Not },
866        expr: None,
867    }
868}
869
870fn build_macro(
871    tcx: TyCtxt<'_>,
872    def_id: DefId,
873    name: Symbol,
874    macro_kinds: MacroKinds,
875) -> clean::ItemKind {
876    match CStore::from_tcx(tcx).load_macro_untracked(tcx, def_id) {
877        LoadedMacro::MacroDef { def, .. } => match macro_kinds {
878            MacroKinds::DERIVE => clean::ProcMacroItem(clean::ProcMacro {
879                kind: MacroKind::Derive,
880                helpers: Vec::new(),
881            }),
882            MacroKinds::ATTR => clean::ProcMacroItem(clean::ProcMacro {
883                kind: MacroKind::Attr,
884                helpers: Vec::new(),
885            }),
886            _ => clean::MacroItem(
887                clean::Macro {
888                    source: utils::display_macro_source(tcx, name, &def),
889                    macro_rules: def.macro_rules,
890                },
891                macro_kinds,
892            ),
893        },
894        LoadedMacro::ProcMacro(ext) => {
895            // Proc macros can only have a single kind
896            let kind = match ext.macro_kinds() {
897                MacroKinds::BANG => MacroKind::Bang,
898                MacroKinds::ATTR => MacroKind::Attr,
899                MacroKinds::DERIVE => MacroKind::Derive,
900                _ => unreachable!(),
901            };
902            clean::ProcMacroItem(clean::ProcMacro { kind, helpers: ext.helper_attrs })
903        }
904    }
905}
906
907fn separate_self_bounds(mut g: clean::Generics) -> (clean::Generics, Vec<clean::GenericBound>) {
908    let mut ty_bounds = Vec::new();
909    g.where_predicates.retain(|pred| match *pred {
910        clean::WherePredicate::BoundPredicate { ty: clean::SelfTy, ref bounds, .. } => {
911            ty_bounds.extend(bounds.iter().cloned());
912            false
913        }
914        _ => true,
915    });
916    (g, ty_bounds)
917}
918
919pub(crate) fn record_extern_trait(cx: &mut DocContext<'_>, did: DefId) {
920    if did.is_local()
921        || cx.external_traits.contains_key(&did)
922        || cx.active_extern_traits.contains(&did)
923    {
924        return;
925    }
926
927    cx.active_extern_traits.insert(did);
928
929    debug!("record_extern_trait: {did:?}");
930    let trait_ = build_trait(cx, did);
931
932    cx.external_traits.insert(did, trait_);
933    cx.active_extern_traits.remove(&did);
934}