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