rustdoc/clean/
inline.rs

1//! Support for inlining external documentation into the current AST.
2
3use std::iter::once;
4use std::sync::Arc;
5
6use rustc_data_structures::fx::FxHashSet;
7use rustc_data_structures::thin_vec::{ThinVec, thin_vec};
8use rustc_hir as hir;
9use rustc_hir::Mutability;
10use rustc_hir::def::{DefKind, MacroKinds, Res};
11use rustc_hir::def_id::{DefId, DefIdSet, LocalDefId, LocalModDefId};
12use rustc_metadata::creader::{CStore, LoadedMacro};
13use rustc_middle::ty::fast_reject::SimplifiedType;
14use rustc_middle::ty::{self, TyCtxt};
15use rustc_span::def_id::LOCAL_CRATE;
16use rustc_span::hygiene::MacroKind;
17use rustc_span::symbol::{Symbol, sym};
18use tracing::{debug, trace};
19
20use super::{Item, extract_cfg_from_attrs};
21use crate::clean::{
22    self, Attributes, CfgInfo, ImplKind, ItemId, Type, clean_bound_vars, clean_generics,
23    clean_impl_item, clean_middle_assoc_item, clean_middle_field, clean_middle_ty,
24    clean_poly_fn_sig, clean_trait_ref_with_constraints, clean_ty, clean_ty_alias_inner_type,
25    clean_ty_generics, 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    cfg_info: &mut CfgInfo,
413) -> (clean::Attributes, Option<Arc<clean::cfg::Cfg>>) {
414    // NOTE: If we have additional attributes (from a re-export),
415    // always insert them first. This ensure that re-export
416    // doc comments show up before the original doc comments
417    // when we render them.
418    if let Some((inner, item_id)) = new_attrs {
419        let mut both = inner.to_vec();
420        both.extend_from_slice(old_attrs);
421        (
422            if let Some(item_id) = item_id {
423                Attributes::from_hir_with_additional(old_attrs, (inner, item_id.to_def_id()))
424            } else {
425                Attributes::from_hir(&both)
426            },
427            extract_cfg_from_attrs(both.iter(), cx.tcx, cfg_info),
428        )
429    } else {
430        (
431            Attributes::from_hir(old_attrs),
432            extract_cfg_from_attrs(old_attrs.iter(), cx.tcx, cfg_info),
433        )
434    }
435}
436
437/// Inline an `impl`, inherent or of a trait. The `did` must be for an `impl`.
438pub(crate) fn build_impl(
439    cx: &mut DocContext<'_>,
440    did: DefId,
441    attrs: Option<(&[hir::Attribute], Option<LocalDefId>)>,
442    ret: &mut Vec<clean::Item>,
443) {
444    if !cx.inlined.insert(did.into()) {
445        return;
446    }
447
448    let tcx = cx.tcx;
449    let _prof_timer = tcx.sess.prof.generic_activity("build_impl");
450
451    let associated_trait = tcx.impl_opt_trait_ref(did).map(ty::EarlyBinder::skip_binder);
452
453    // Do not inline compiler-internal items unless we're a compiler-internal crate.
454    let is_compiler_internal = |did| {
455        tcx.lookup_stability(did)
456            .is_some_and(|stab| stab.is_unstable() && stab.feature == sym::rustc_private)
457    };
458    let document_compiler_internal = is_compiler_internal(LOCAL_CRATE.as_def_id());
459    let is_directly_public = |cx: &mut DocContext<'_>, did| {
460        cx.cache.effective_visibilities.is_directly_public(tcx, did)
461            && (document_compiler_internal || !is_compiler_internal(did))
462    };
463
464    // Only inline impl if the implemented trait is
465    // reachable in rustdoc generated documentation
466    if !did.is_local()
467        && let Some(traitref) = associated_trait
468        && !is_directly_public(cx, traitref.def_id)
469    {
470        return;
471    }
472
473    let impl_item = match did.as_local() {
474        Some(did) => match &tcx.hir_expect_item(did).kind {
475            hir::ItemKind::Impl(impl_) => Some(impl_),
476            _ => panic!("`DefID` passed to `build_impl` is not an `impl"),
477        },
478        None => None,
479    };
480
481    let for_ = match &impl_item {
482        Some(impl_) => clean_ty(impl_.self_ty, cx),
483        None => clean_middle_ty(
484            ty::Binder::dummy(tcx.type_of(did).instantiate_identity()),
485            cx,
486            Some(did),
487            None,
488        ),
489    };
490
491    // Only inline impl if the implementing type is
492    // reachable in rustdoc generated documentation
493    if !did.is_local()
494        && let Some(did) = for_.def_id(&cx.cache)
495        && !is_directly_public(cx, did)
496    {
497        return;
498    }
499
500    let document_hidden = cx.render_options.document_hidden;
501    let (trait_items, generics) = match impl_item {
502        Some(impl_) => (
503            impl_
504                .items
505                .iter()
506                .map(|&item| tcx.hir_impl_item(item))
507                .filter(|item| {
508                    // Filter out impl items whose corresponding trait item has `doc(hidden)`
509                    // not to document such impl items.
510                    // For inherent impls, we don't do any filtering, because that's already done in strip_hidden.rs.
511
512                    // When `--document-hidden-items` is passed, we don't
513                    // do any filtering, too.
514                    if document_hidden {
515                        return true;
516                    }
517                    if let Some(associated_trait) = associated_trait {
518                        let assoc_tag = match item.kind {
519                            hir::ImplItemKind::Const(..) => ty::AssocTag::Const,
520                            hir::ImplItemKind::Fn(..) => ty::AssocTag::Fn,
521                            hir::ImplItemKind::Type(..) => ty::AssocTag::Type,
522                        };
523                        let trait_item = tcx
524                            .associated_items(associated_trait.def_id)
525                            .find_by_ident_and_kind(
526                                tcx,
527                                item.ident,
528                                assoc_tag,
529                                associated_trait.def_id,
530                            )
531                            .unwrap(); // SAFETY: For all impl items there exists trait item that has the same name.
532                        !tcx.is_doc_hidden(trait_item.def_id)
533                    } else {
534                        true
535                    }
536                })
537                .map(|item| clean_impl_item(item, cx))
538                .collect::<Vec<_>>(),
539            clean_generics(impl_.generics, cx),
540        ),
541        None => (
542            tcx.associated_items(did)
543                .in_definition_order()
544                .filter(|item| !item.is_impl_trait_in_trait())
545                .filter(|item| {
546                    // If this is a trait impl, filter out associated items whose corresponding item
547                    // in the associated trait is marked `doc(hidden)`.
548                    // If this is an inherent impl, filter out private associated items.
549                    if let Some(associated_trait) = associated_trait {
550                        let trait_item = tcx
551                            .associated_items(associated_trait.def_id)
552                            .find_by_ident_and_kind(
553                                tcx,
554                                item.ident(tcx),
555                                item.as_tag(),
556                                associated_trait.def_id,
557                            )
558                            .unwrap(); // corresponding associated item has to exist
559                        document_hidden || !tcx.is_doc_hidden(trait_item.def_id)
560                    } else {
561                        item.visibility(tcx).is_public()
562                    }
563                })
564                .map(|item| clean_middle_assoc_item(item, cx))
565                .collect::<Vec<_>>(),
566            clean::enter_impl_trait(cx, |cx| clean_ty_generics(cx, did)),
567        ),
568    };
569    let polarity = if associated_trait.is_some() {
570        tcx.impl_polarity(did)
571    } else {
572        ty::ImplPolarity::Positive
573    };
574    let trait_ = associated_trait
575        .map(|t| clean_trait_ref_with_constraints(cx, ty::Binder::dummy(t), ThinVec::new()));
576    if trait_.as_ref().map(|t| t.def_id()) == tcx.lang_items().deref_trait() {
577        super::build_deref_target_impls(cx, &trait_items, ret);
578    }
579
580    if !document_hidden {
581        // Return if the trait itself or any types of the generic parameters are doc(hidden).
582        let mut stack: Vec<&Type> = vec![&for_];
583
584        if let Some(did) = trait_.as_ref().map(|t| t.def_id())
585            && tcx.is_doc_hidden(did)
586        {
587            return;
588        }
589
590        if let Some(generics) = trait_.as_ref().and_then(|t| t.generics()) {
591            stack.extend(generics);
592        }
593
594        while let Some(ty) = stack.pop() {
595            if let Some(did) = ty.def_id(&cx.cache)
596                && tcx.is_doc_hidden(did)
597            {
598                return;
599            }
600            if let Some(generics) = ty.generics() {
601                stack.extend(generics);
602            }
603        }
604    }
605
606    if let Some(did) = trait_.as_ref().map(|t| t.def_id()) {
607        cx.with_param_env(did, |cx| {
608            record_extern_trait(cx, did);
609        });
610    }
611
612    // In here, we pass an empty `CfgInfo` because the computation of `cfg` happens later, so it
613    // doesn't matter at this point.
614    //
615    // We need to pass this empty `CfgInfo` because `merge_attrs` is used when computing the `cfg`.
616    let (merged_attrs, cfg) = merge_attrs(cx, load_attrs(cx, did), attrs, &mut CfgInfo::default());
617    trace!("merged_attrs={merged_attrs:?}");
618
619    trace!(
620        "build_impl: impl {:?} for {:?}",
621        trait_.as_ref().map(|t| t.def_id()),
622        for_.def_id(&cx.cache)
623    );
624    ret.push(clean::Item::from_def_id_and_attrs_and_parts(
625        did,
626        None,
627        clean::ImplItem(Box::new(clean::Impl {
628            safety: hir::Safety::Safe,
629            generics,
630            trait_,
631            for_,
632            items: trait_items,
633            polarity,
634            kind: if utils::has_doc_flag(tcx, did, sym::fake_variadic) {
635                ImplKind::FakeVariadic
636            } else {
637                ImplKind::Normal
638            },
639        })),
640        merged_attrs,
641        cfg,
642    ));
643}
644
645fn build_module(cx: &mut DocContext<'_>, did: DefId, visited: &mut DefIdSet) -> clean::Module {
646    let items = build_module_items(cx, did, visited, &mut FxHashSet::default(), None, None);
647
648    let span = clean::Span::new(cx.tcx.def_span(did));
649    clean::Module { items, span }
650}
651
652fn build_module_items(
653    cx: &mut DocContext<'_>,
654    did: DefId,
655    visited: &mut DefIdSet,
656    inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
657    allowed_def_ids: Option<&DefIdSet>,
658    attrs: Option<(&[hir::Attribute], Option<LocalDefId>)>,
659) -> Vec<clean::Item> {
660    let mut items = Vec::new();
661
662    // If we're re-exporting a re-export it may actually re-export something in
663    // two namespaces, so the target may be listed twice. Make sure we only
664    // visit each node at most once.
665    for item in cx.tcx.module_children(did).iter() {
666        if item.vis.is_public() {
667            let res = item.res.expect_non_local();
668            if let Some(def_id) = res.opt_def_id()
669                && let Some(allowed_def_ids) = allowed_def_ids
670                && !allowed_def_ids.contains(&def_id)
671            {
672                continue;
673            }
674            if let Some(def_id) = res.mod_def_id() {
675                // If we're inlining a glob import, it's possible to have
676                // two distinct modules with the same name. We don't want to
677                // inline it, or mark any of its contents as visited.
678                if did == def_id
679                    || inlined_names.contains(&(ItemType::Module, item.ident.name))
680                    || !visited.insert(def_id)
681                {
682                    continue;
683                }
684            }
685            if let Res::PrimTy(p) = res {
686                // Primitive types can't be inlined so generate an import instead.
687                let prim_ty = clean::PrimitiveType::from(p);
688                items.push(clean::Item {
689                    inner: Box::new(clean::ItemInner {
690                        name: None,
691                        // We can use the item's `DefId` directly since the only information ever
692                        // used from it is `DefId.krate`.
693                        item_id: ItemId::DefId(did),
694                        attrs: Default::default(),
695                        stability: None,
696                        kind: clean::ImportItem(clean::Import::new_simple(
697                            item.ident.name,
698                            clean::ImportSource {
699                                path: clean::Path {
700                                    res,
701                                    segments: thin_vec![clean::PathSegment {
702                                        name: prim_ty.as_sym(),
703                                        args: clean::GenericArgs::AngleBracketed {
704                                            args: Default::default(),
705                                            constraints: ThinVec::new(),
706                                        },
707                                    }],
708                                },
709                                did: None,
710                            },
711                            true,
712                        )),
713                        cfg: None,
714                        inline_stmt_id: None,
715                    }),
716                });
717            } else if let Some(i) = try_inline(cx, res, item.ident.name, attrs, visited) {
718                items.extend(i)
719            }
720        }
721    }
722
723    items
724}
725
726pub(crate) fn print_inlined_const(tcx: TyCtxt<'_>, did: DefId) -> String {
727    if let Some(did) = did.as_local() {
728        let hir_id = tcx.local_def_id_to_hir_id(did);
729        rustc_hir_pretty::id_to_string(&tcx, hir_id)
730    } else {
731        tcx.rendered_const(did).clone()
732    }
733}
734
735fn build_const_item(cx: &mut DocContext<'_>, def_id: DefId) -> clean::Constant {
736    let mut generics = clean_ty_generics(cx, def_id);
737    clean::simplify::move_bounds_to_generic_parameters(&mut generics);
738    let ty = clean_middle_ty(
739        ty::Binder::dummy(cx.tcx.type_of(def_id).instantiate_identity()),
740        cx,
741        None,
742        None,
743    );
744    clean::Constant { generics, type_: ty, kind: clean::ConstantKind::Extern { def_id } }
745}
746
747fn build_static(cx: &mut DocContext<'_>, did: DefId, mutable: bool) -> clean::Static {
748    clean::Static {
749        type_: Box::new(clean_middle_ty(
750            ty::Binder::dummy(cx.tcx.type_of(did).instantiate_identity()),
751            cx,
752            Some(did),
753            None,
754        )),
755        mutability: if mutable { Mutability::Mut } else { Mutability::Not },
756        expr: None,
757    }
758}
759
760fn build_macro(
761    cx: &mut DocContext<'_>,
762    def_id: DefId,
763    name: Symbol,
764    macro_kinds: MacroKinds,
765) -> clean::ItemKind {
766    match CStore::from_tcx(cx.tcx).load_macro_untracked(def_id, cx.tcx) {
767        // FIXME: handle attributes and derives that aren't proc macros, and macros with multiple
768        // kinds
769        LoadedMacro::MacroDef { def, .. } => match macro_kinds {
770            MacroKinds::BANG => clean::MacroItem(clean::Macro {
771                source: utils::display_macro_source(cx, name, &def),
772                macro_rules: def.macro_rules,
773            }),
774            MacroKinds::DERIVE => clean::ProcMacroItem(clean::ProcMacro {
775                kind: MacroKind::Derive,
776                helpers: Vec::new(),
777            }),
778            MacroKinds::ATTR => clean::ProcMacroItem(clean::ProcMacro {
779                kind: MacroKind::Attr,
780                helpers: Vec::new(),
781            }),
782            _ => todo!("Handle macros with multiple kinds"),
783        },
784        LoadedMacro::ProcMacro(ext) => {
785            // Proc macros can only have a single kind
786            let kind = match ext.macro_kinds() {
787                MacroKinds::BANG => MacroKind::Bang,
788                MacroKinds::ATTR => MacroKind::Attr,
789                MacroKinds::DERIVE => MacroKind::Derive,
790                _ => unreachable!(),
791            };
792            clean::ProcMacroItem(clean::ProcMacro { kind, helpers: ext.helper_attrs })
793        }
794    }
795}
796
797fn separate_self_bounds(mut g: clean::Generics) -> (clean::Generics, Vec<clean::GenericBound>) {
798    let mut ty_bounds = Vec::new();
799    g.where_predicates.retain(|pred| match *pred {
800        clean::WherePredicate::BoundPredicate { ty: clean::SelfTy, ref bounds, .. } => {
801            ty_bounds.extend(bounds.iter().cloned());
802            false
803        }
804        _ => true,
805    });
806    (g, ty_bounds)
807}
808
809pub(crate) fn record_extern_trait(cx: &mut DocContext<'_>, did: DefId) {
810    if did.is_local()
811        || cx.external_traits.contains_key(&did)
812        || cx.active_extern_traits.contains(&did)
813    {
814        return;
815    }
816
817    cx.active_extern_traits.insert(did);
818
819    debug!("record_extern_trait: {did:?}");
820    let trait_ = build_trait(cx, did);
821
822    cx.external_traits.insert(did, trait_);
823    cx.active_extern_traits.remove(&did);
824}