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