[go: up one dir, main page]

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