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