1 //! Support for inlining external documentation into the current AST.
7 use rustc_data_structures::fx::FxHashSet;
8 use rustc_data_structures::thin_vec::ThinVec;
10 use rustc_hir::def::{DefKind, Res};
11 use rustc_hir::def_id::DefId;
12 use rustc_hir::Mutability;
13 use rustc_metadata::creader::{CStore, LoadedMacro};
14 use rustc_middle::ty::{self, TyCtxt};
15 use rustc_span::hygiene::MacroKind;
16 use rustc_span::symbol::{kw, sym, Symbol};
19 self, clean_fn_decl_from_did_and_sig, clean_generics, clean_impl_item, clean_middle_assoc_item,
20 clean_middle_field, clean_middle_ty, clean_trait_ref_with_bindings, clean_ty,
21 clean_ty_generics, clean_variant_def, clean_visibility, utils, Attributes, AttributesExt,
22 ImplKind, ItemId, Type, Visibility,
24 use crate::core::DocContext;
25 use crate::formats::item_type::ItemType;
27 type Attrs<'hir> = &'hir [ast::Attribute];
29 /// Attempt to inline a definition into this AST.
31 /// This function will fetch the definition specified, and if it is
32 /// from another crate it will attempt to inline the documentation
33 /// from the other crate into this crate.
35 /// This is primarily used for `pub use` statements which are, in general,
36 /// implementation details. Inlining the documentation should help provide a
37 /// better experience when reading the documentation in this use case.
39 /// The returned value is `None` if the definition could not be inlined,
40 /// and `Some` of a vector of items if it was successfully expanded.
42 /// `parent_module` refers to the parent of the *re-export*, not the original item.
43 pub(crate) fn try_inline(
44 cx: &mut DocContext<'_>,
46 import_def_id: Option<DefId>,
49 attrs: Option<Attrs<'_>>,
50 visited: &mut FxHashSet<DefId>,
51 ) -> Option<Vec<clean::Item>> {
52 let did = res.opt_def_id()?;
56 let mut ret = Vec::new();
58 debug!("attrs={:?}", attrs);
59 let attrs_clone = attrs;
61 let kind = match res {
62 Res::Def(DefKind::Trait, did) => {
63 record_extern_fqn(cx, did, ItemType::Trait);
64 build_impls(cx, Some(parent_module), did, attrs, &mut ret);
65 clean::TraitItem(build_external_trait(cx, did))
67 Res::Def(DefKind::Fn, did) => {
68 record_extern_fqn(cx, did, ItemType::Function);
69 clean::FunctionItem(build_external_function(cx, did))
71 Res::Def(DefKind::Struct, did) => {
72 record_extern_fqn(cx, did, ItemType::Struct);
73 build_impls(cx, Some(parent_module), did, attrs, &mut ret);
74 clean::StructItem(build_struct(cx, did))
76 Res::Def(DefKind::Union, did) => {
77 record_extern_fqn(cx, did, ItemType::Union);
78 build_impls(cx, Some(parent_module), did, attrs, &mut ret);
79 clean::UnionItem(build_union(cx, did))
81 Res::Def(DefKind::TyAlias, did) => {
82 record_extern_fqn(cx, did, ItemType::Typedef);
83 build_impls(cx, Some(parent_module), did, attrs, &mut ret);
84 clean::TypedefItem(build_type_alias(cx, did))
86 Res::Def(DefKind::Enum, did) => {
87 record_extern_fqn(cx, did, ItemType::Enum);
88 build_impls(cx, Some(parent_module), did, attrs, &mut ret);
89 clean::EnumItem(build_enum(cx, did))
91 Res::Def(DefKind::ForeignTy, did) => {
92 record_extern_fqn(cx, did, ItemType::ForeignType);
93 build_impls(cx, Some(parent_module), did, attrs, &mut ret);
94 clean::ForeignTypeItem
96 // Never inline enum variants but leave them shown as re-exports.
97 Res::Def(DefKind::Variant, _) => return None,
98 // Assume that enum variants and struct types are re-exported next to
99 // their constructors.
100 Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) => return Some(Vec::new()),
101 Res::Def(DefKind::Mod, did) => {
102 record_extern_fqn(cx, did, ItemType::Module);
103 clean::ModuleItem(build_module(cx, did, visited))
105 Res::Def(DefKind::Static(_), did) => {
106 record_extern_fqn(cx, did, ItemType::Static);
107 clean::StaticItem(build_static(cx, did, cx.tcx.is_mutable_static(did)))
109 Res::Def(DefKind::Const, did) => {
110 record_extern_fqn(cx, did, ItemType::Constant);
111 clean::ConstantItem(build_const(cx, did))
113 Res::Def(DefKind::Macro(kind), did) => {
114 let mac = build_macro(cx, did, name, import_def_id);
116 let type_kind = match kind {
117 MacroKind::Bang => ItemType::Macro,
118 MacroKind::Attr => ItemType::ProcAttribute,
119 MacroKind::Derive => ItemType::ProcDerive,
121 record_extern_fqn(cx, did, type_kind);
127 let (attrs, cfg) = merge_attrs(cx, Some(parent_module), load_attrs(cx, did), attrs_clone);
128 cx.inlined.insert(did.into());
129 let mut item = clean::Item::from_def_id_and_attrs_and_parts(
137 if let Some(import_def_id) = import_def_id {
138 // The visibility needs to reflect the one from the reexport and not from the "source" DefId.
139 item.visibility = clean_visibility(cx.tcx.visibility(import_def_id));
145 pub(crate) fn try_inline_glob(
146 cx: &mut DocContext<'_>,
148 visited: &mut FxHashSet<DefId>,
149 inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
150 ) -> Option<Vec<clean::Item>> {
151 let did = res.opt_def_id()?;
157 Res::Def(DefKind::Mod, did) => {
158 let mut items = build_module_items(cx, did, visited, inlined_names);
159 items.drain_filter(|item| {
160 if let Some(name) = item.name {
161 // If an item with the same type and name already exists,
162 // it takes priority over the inlined stuff.
163 !inlined_names.insert((item.type_(), name))
170 // glob imports on things like enums aren't inlined even for local exports, so just bail
175 pub(crate) fn load_attrs<'hir>(cx: &DocContext<'hir>, did: DefId) -> Attrs<'hir> {
176 cx.tcx.get_attrs_unchecked(did)
179 /// Record an external fully qualified name in the external_paths cache.
181 /// These names are used later on by HTML rendering to generate things like
182 /// source links back to the original item.
183 pub(crate) fn record_extern_fqn(cx: &mut DocContext<'_>, did: DefId, kind: ItemType) {
184 let crate_name = cx.tcx.crate_name(did.krate);
187 cx.tcx.def_path(did).data.into_iter().filter_map(|elem| elem.data.get_opt_name());
188 let fqn = if let ItemType::Macro = kind {
189 // Check to see if it is a macro 2.0 or built-in macro
191 CStore::from_tcx(cx.tcx).load_macro_untracked(did, cx.sess()),
192 LoadedMacro::MacroDef(def, _)
193 if matches!(&def.kind, ast::ItemKind::MacroDef(ast_def)
194 if !ast_def.macro_rules)
196 once(crate_name).chain(relative).collect()
198 vec![crate_name, relative.last().expect("relative was empty")]
201 once(crate_name).chain(relative).collect()
205 cx.cache.exact_paths.insert(did, fqn);
207 cx.cache.external_paths.insert(did, (fqn, kind));
211 pub(crate) fn build_external_trait(cx: &mut DocContext<'_>, did: DefId) -> clean::Trait {
214 .associated_items(did)
215 .in_definition_order()
217 // When building an external trait, the cleaned trait will have all items public,
218 // which causes methods to have a `pub` prefix, which is invalid since items in traits
219 // can not have a visibility prefix. Thus we override the visibility here manually.
220 // See https://github.com/rust-lang/rust/issues/81274
221 clean::Item { visibility: Visibility::Inherited, ..clean_middle_assoc_item(item, cx) }
225 let predicates = cx.tcx.predicates_of(did);
226 let generics = clean_ty_generics(cx, cx.tcx.generics_of(did), predicates);
227 let generics = filter_non_trait_generics(did, generics);
228 let (generics, supertrait_bounds) = separate_supertrait_bounds(generics);
229 clean::Trait { def_id: did, generics, items: trait_items, bounds: supertrait_bounds }
232 fn build_external_function<'tcx>(cx: &mut DocContext<'tcx>, did: DefId) -> Box<clean::Function> {
233 let sig = cx.tcx.fn_sig(did);
235 let predicates = cx.tcx.predicates_of(did);
236 let (generics, decl) = clean::enter_impl_trait(cx, |cx| {
237 // NOTE: generics need to be cleaned before the decl!
238 let generics = clean_ty_generics(cx, cx.tcx.generics_of(did), predicates);
239 let decl = clean_fn_decl_from_did_and_sig(cx, Some(did), sig);
242 Box::new(clean::Function { decl, generics })
245 fn build_enum(cx: &mut DocContext<'_>, did: DefId) -> clean::Enum {
246 let predicates = cx.tcx.explicit_predicates_of(did);
249 generics: clean_ty_generics(cx, cx.tcx.generics_of(did), predicates),
250 variants: cx.tcx.adt_def(did).variants().iter().map(|v| clean_variant_def(v, cx)).collect(),
254 fn build_struct(cx: &mut DocContext<'_>, did: DefId) -> clean::Struct {
255 let predicates = cx.tcx.explicit_predicates_of(did);
256 let variant = cx.tcx.adt_def(did).non_enum_variant();
259 struct_type: variant.ctor_kind,
260 generics: clean_ty_generics(cx, cx.tcx.generics_of(did), predicates),
261 fields: variant.fields.iter().map(|x| clean_middle_field(x, cx)).collect(),
265 fn build_union(cx: &mut DocContext<'_>, did: DefId) -> clean::Union {
266 let predicates = cx.tcx.explicit_predicates_of(did);
267 let variant = cx.tcx.adt_def(did).non_enum_variant();
269 let generics = clean_ty_generics(cx, cx.tcx.generics_of(did), predicates);
270 let fields = variant.fields.iter().map(|x| clean_middle_field(x, cx)).collect();
271 clean::Union { generics, fields }
274 fn build_type_alias(cx: &mut DocContext<'_>, did: DefId) -> Box<clean::Typedef> {
275 let predicates = cx.tcx.explicit_predicates_of(did);
276 let type_ = clean_middle_ty(cx.tcx.type_of(did), cx, Some(did));
278 Box::new(clean::Typedef {
280 generics: clean_ty_generics(cx, cx.tcx.generics_of(did), predicates),
285 /// Builds all inherent implementations of an ADT (struct/union/enum) or Trait item/path/reexport.
286 pub(crate) fn build_impls(
287 cx: &mut DocContext<'_>,
288 parent_module: Option<DefId>,
290 attrs: Option<Attrs<'_>>,
291 ret: &mut Vec<clean::Item>,
293 let _prof_timer = cx.tcx.sess.prof.generic_activity("build_inherent_impls");
296 // for each implementation of an item represented by `did`, build the clean::Item for that impl
297 for &did in tcx.inherent_impls(did).iter() {
298 build_impl(cx, parent_module, did, attrs, ret);
302 /// `parent_module` refers to the parent of the re-export, not the original item
304 cx: &mut DocContext<'_>,
305 parent_module: Option<DefId>,
306 old_attrs: Attrs<'_>,
307 new_attrs: Option<Attrs<'_>>,
308 ) -> (clean::Attributes, Option<Arc<clean::cfg::Cfg>>) {
309 // NOTE: If we have additional attributes (from a re-export),
310 // always insert them first. This ensure that re-export
311 // doc comments show up before the original doc comments
312 // when we render them.
313 if let Some(inner) = new_attrs {
314 let mut both = inner.to_vec();
315 both.extend_from_slice(old_attrs);
317 if let Some(new_id) = parent_module {
318 Attributes::from_ast_with_additional(old_attrs, (inner, new_id))
320 Attributes::from_ast(&both)
322 both.cfg(cx.tcx, &cx.cache.hidden_cfg),
325 (Attributes::from_ast(&old_attrs), old_attrs.cfg(cx.tcx, &cx.cache.hidden_cfg))
329 /// Inline an `impl`, inherent or of a trait. The `did` must be for an `impl`.
330 pub(crate) fn build_impl(
331 cx: &mut DocContext<'_>,
332 parent_module: Option<DefId>,
334 attrs: Option<Attrs<'_>>,
335 ret: &mut Vec<clean::Item>,
337 if !cx.inlined.insert(did.into()) {
341 let _prof_timer = cx.tcx.sess.prof.generic_activity("build_impl");
344 let associated_trait = tcx.impl_trait_ref(did);
346 // Only inline impl if the implemented trait is
347 // reachable in rustdoc generated documentation
349 if let Some(traitref) = associated_trait {
350 let did = traitref.def_id;
351 if !cx.cache.access_levels.is_public(did) {
355 if let Some(stab) = tcx.lookup_stability(did) {
356 if stab.is_unstable() && stab.feature == sym::rustc_private {
363 let impl_item = match did.as_local() {
364 Some(did) => match &tcx.hir().expect_item(did).kind {
365 hir::ItemKind::Impl(impl_) => Some(impl_),
366 _ => panic!("`DefID` passed to `build_impl` is not an `impl"),
371 let for_ = match &impl_item {
372 Some(impl_) => clean_ty(impl_.self_ty, cx),
373 None => clean_middle_ty(tcx.type_of(did), cx, Some(did)),
376 // Only inline impl if the implementing type is
377 // reachable in rustdoc generated documentation
379 if let Some(did) = for_.def_id(&cx.cache) {
380 if !cx.cache.access_levels.is_public(did) {
384 if let Some(stab) = tcx.lookup_stability(did) {
385 if stab.is_unstable() && stab.feature == sym::rustc_private {
392 let document_hidden = cx.render_options.document_hidden;
393 let predicates = tcx.explicit_predicates_of(did);
394 let (trait_items, generics) = match impl_item {
399 .map(|item| tcx.hir().impl_item(item.id))
401 // Filter out impl items whose corresponding trait item has `doc(hidden)`
402 // not to document such impl items.
403 // For inherent impls, we don't do any filtering, because that's already done in strip_hidden.rs.
405 // When `--document-hidden-items` is passed, we don't
406 // do any filtering, too.
410 if let Some(associated_trait) = associated_trait {
411 let assoc_kind = match item.kind {
412 hir::ImplItemKind::Const(..) => ty::AssocKind::Const,
413 hir::ImplItemKind::Fn(..) => ty::AssocKind::Fn,
414 hir::ImplItemKind::TyAlias(..) => ty::AssocKind::Type,
417 .associated_items(associated_trait.def_id)
418 .find_by_name_and_kind(
422 associated_trait.def_id,
424 .unwrap(); // SAFETY: For all impl items there exists trait item that has the same name.
425 !tcx.is_doc_hidden(trait_item.def_id)
430 .map(|item| clean_impl_item(item, cx))
431 .collect::<Vec<_>>(),
432 clean_generics(impl_.generics, cx),
435 tcx.associated_items(did)
436 .in_definition_order()
438 // If this is a trait impl, filter out associated items whose corresponding item
439 // in the associated trait is marked `doc(hidden)`.
440 // If this is an inherent impl, filter out private associated items.
441 if let Some(associated_trait) = associated_trait {
443 .associated_items(associated_trait.def_id)
444 .find_by_name_and_kind(
448 associated_trait.def_id,
450 .unwrap(); // corresponding associated item has to exist
451 !tcx.is_doc_hidden(trait_item.def_id)
453 item.visibility(tcx).is_public()
456 .map(|item| clean_middle_assoc_item(item, cx))
457 .collect::<Vec<_>>(),
458 clean::enter_impl_trait(cx, |cx| {
459 clean_ty_generics(cx, tcx.generics_of(did), predicates)
463 let polarity = tcx.impl_polarity(did);
464 let trait_ = associated_trait.map(|t| clean_trait_ref_with_bindings(cx, t, &[]));
465 if trait_.as_ref().map(|t| t.def_id()) == tcx.lang_items().deref_trait() {
466 super::build_deref_target_impls(cx, &trait_items, ret);
469 // Return if the trait itself or any types of the generic parameters are doc(hidden).
470 let mut stack: Vec<&Type> = vec![&for_];
472 if let Some(did) = trait_.as_ref().map(|t| t.def_id()) {
473 if tcx.is_doc_hidden(did) {
477 if let Some(generics) = trait_.as_ref().and_then(|t| t.generics()) {
478 stack.extend(generics);
481 while let Some(ty) = stack.pop() {
482 if let Some(did) = ty.def_id(&cx.cache) {
483 if tcx.is_doc_hidden(did) {
487 if let Some(generics) = ty.generics() {
488 stack.extend(generics);
492 if let Some(did) = trait_.as_ref().map(|t| t.def_id()) {
493 record_extern_trait(cx, did);
496 let (merged_attrs, cfg) = merge_attrs(cx, parent_module, load_attrs(cx, did), attrs);
497 trace!("merged_attrs={:?}", merged_attrs);
500 "build_impl: impl {:?} for {:?}",
501 trait_.as_ref().map(|t| t.def_id()),
502 for_.def_id(&cx.cache)
504 ret.push(clean::Item::from_def_id_and_attrs_and_parts(
507 clean::ImplItem(Box::new(clean::Impl {
508 unsafety: hir::Unsafety::Normal,
514 kind: if utils::has_doc_flag(tcx, did, sym::fake_variadic) {
515 ImplKind::FakeVaradic
520 Box::new(merged_attrs),
527 cx: &mut DocContext<'_>,
529 visited: &mut FxHashSet<DefId>,
531 let items = build_module_items(cx, did, visited, &mut FxHashSet::default());
533 let span = clean::Span::new(cx.tcx.def_span(did));
534 clean::Module { items, span }
537 fn build_module_items(
538 cx: &mut DocContext<'_>,
540 visited: &mut FxHashSet<DefId>,
541 inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
542 ) -> Vec<clean::Item> {
543 let mut items = Vec::new();
545 // If we're re-exporting a re-export it may actually re-export something in
546 // two namespaces, so the target may be listed twice. Make sure we only
547 // visit each node at most once.
548 for &item in cx.tcx.module_children(did).iter() {
549 if item.vis.is_public() {
550 let res = item.res.expect_non_local();
551 if let Some(def_id) = res.mod_def_id() {
552 // If we're inlining a glob import, it's possible to have
553 // two distinct modules with the same name. We don't want to
554 // inline it, or mark any of its contents as visited.
556 || inlined_names.contains(&(ItemType::Module, item.ident.name))
557 || !visited.insert(def_id)
562 if let Res::PrimTy(p) = res {
563 // Primitive types can't be inlined so generate an import instead.
564 let prim_ty = clean::PrimitiveType::from(p);
565 items.push(clean::Item {
567 attrs: Box::new(clean::Attributes::default()),
568 item_id: ItemId::Primitive(prim_ty, did.krate),
569 visibility: clean::Public,
570 kind: Box::new(clean::ImportItem(clean::Import::new_simple(
572 clean::ImportSource {
575 segments: vec![clean::PathSegment {
576 name: prim_ty.as_sym(),
577 args: clean::GenericArgs::AngleBracketed {
578 args: Default::default(),
579 bindings: ThinVec::new(),
589 } else if let Some(i) = try_inline(cx, did, None, res, item.ident.name, None, visited) {
598 pub(crate) fn print_inlined_const(tcx: TyCtxt<'_>, did: DefId) -> String {
599 if let Some(did) = did.as_local() {
600 let hir_id = tcx.hir().local_def_id_to_hir_id(did);
601 rustc_hir_pretty::id_to_string(&tcx.hir(), hir_id)
603 tcx.rendered_const(did).clone()
607 fn build_const(cx: &mut DocContext<'_>, def_id: DefId) -> clean::Constant {
609 type_: clean_middle_ty(cx.tcx.type_of(def_id), cx, Some(def_id)),
610 kind: clean::ConstantKind::Extern { def_id },
614 fn build_static(cx: &mut DocContext<'_>, did: DefId, mutable: bool) -> clean::Static {
616 type_: clean_middle_ty(cx.tcx.type_of(did), cx, Some(did)),
617 mutability: if mutable { Mutability::Mut } else { Mutability::Not },
623 cx: &mut DocContext<'_>,
626 import_def_id: Option<DefId>,
627 ) -> clean::ItemKind {
628 match CStore::from_tcx(cx.tcx).load_macro_untracked(def_id, cx.sess()) {
629 LoadedMacro::MacroDef(item_def, _) => {
630 if let ast::ItemKind::MacroDef(ref def) = item_def.kind {
631 let vis = clean_visibility(cx.tcx.visibility(import_def_id.unwrap_or(def_id)));
632 clean::MacroItem(clean::Macro {
633 source: utils::display_macro_source(cx, name, def, def_id, vis),
639 LoadedMacro::ProcMacro(ext) => clean::ProcMacroItem(clean::ProcMacro {
640 kind: ext.macro_kind(),
641 helpers: ext.helper_attrs,
646 /// A trait's generics clause actually contains all of the predicates for all of
647 /// its associated types as well. We specifically move these clauses to the
648 /// associated types instead when displaying, so when we're generating the
649 /// generics for the trait itself we need to be sure to remove them.
650 /// We also need to remove the implied "recursive" Self: Trait bound.
652 /// The inverse of this filtering logic can be found in the `Clean`
653 /// implementation for `AssociatedType`
654 fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean::Generics {
655 for pred in &mut g.where_predicates {
657 clean::WherePredicate::BoundPredicate {
658 ty: clean::Generic(ref s),
661 } if *s == kw::SelfUpper => {
662 bounds.retain(|bound| match bound {
663 clean::GenericBound::TraitBound(clean::PolyTrait { trait_, .. }, _) => {
664 trait_.def_id() != trait_did
673 g.where_predicates.retain(|pred| match pred {
674 clean::WherePredicate::BoundPredicate {
675 ty: clean::QPath { self_type: box clean::Generic(ref s), trait_, .. },
678 } => !(bounds.is_empty() || *s == kw::SelfUpper && trait_.def_id() == trait_did),
684 /// Supertrait bounds for a trait are also listed in the generics coming from
685 /// the metadata for a crate, so we want to separate those out and create a new
686 /// list of explicit supertrait bounds to render nicely.
687 fn separate_supertrait_bounds(
688 mut g: clean::Generics,
689 ) -> (clean::Generics, Vec<clean::GenericBound>) {
690 let mut ty_bounds = Vec::new();
691 g.where_predicates.retain(|pred| match *pred {
692 clean::WherePredicate::BoundPredicate { ty: clean::Generic(ref s), ref bounds, .. }
693 if *s == kw::SelfUpper =>
695 ty_bounds.extend(bounds.iter().cloned());
703 pub(crate) fn record_extern_trait(cx: &mut DocContext<'_>, did: DefId) {
709 if cx.external_traits.borrow().contains_key(&did) || cx.active_extern_traits.contains(&did)
716 cx.active_extern_traits.insert(did);
719 debug!("record_extern_trait: {:?}", did);
720 let trait_ = build_external_trait(cx, did);
722 let trait_ = clean::TraitWithExtraInfo {
724 is_notable: clean::utils::has_doc_flag(cx.tcx, did, sym::notable_trait),
726 cx.external_traits.borrow_mut().insert(did, trait_);
727 cx.active_extern_traits.remove(&did);