1 //! Support for inlining external documentation into the current AST.
9 use rustc_data_structures::fx::FxHashSet;
11 use rustc_hir::def::{DefKind, Res};
12 use rustc_hir::def_id::DefId;
13 use rustc_hir::Mutability;
14 use rustc_metadata::creader::{CStore, LoadedMacro};
15 use rustc_middle::ty::{self, TyCtxt};
16 use rustc_span::hygiene::MacroKind;
17 use rustc_span::symbol::{kw, sym, Symbol};
20 self, clean_fn_decl_from_did_and_sig, clean_generics, clean_impl_item, clean_middle_assoc_item,
21 clean_middle_field, clean_middle_ty, clean_trait_ref_with_bindings, clean_ty,
22 clean_ty_generics, clean_variant_def, clean_visibility, utils, Attributes, AttributesExt,
23 ImplKind, ItemId, Type, Visibility,
25 use crate::core::DocContext;
26 use crate::formats::item_type::ItemType;
28 type Attrs<'hir> = &'hir [ast::Attribute];
30 /// Attempt to inline a definition into this AST.
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.
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.
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.
43 /// `parent_module` refers to the parent of the *re-export*, not the original item.
44 pub(crate) fn try_inline(
45 cx: &mut DocContext<'_>,
47 import_def_id: Option<DefId>,
50 attrs: Option<Attrs<'_>>,
51 visited: &mut FxHashSet<DefId>,
52 ) -> Option<Vec<clean::Item>> {
53 let did = res.opt_def_id()?;
57 let mut ret = Vec::new();
59 debug!("attrs={:?}", attrs);
60 let attrs_clone = attrs;
62 let kind = match res {
63 Res::Def(DefKind::Trait, did) => {
64 record_extern_fqn(cx, did, ItemType::Trait);
65 build_impls(cx, Some(parent_module), did, attrs, &mut ret);
66 clean::TraitItem(Box::new(build_external_trait(cx, did)))
68 Res::Def(DefKind::Fn, did) => {
69 record_extern_fqn(cx, did, ItemType::Function);
70 clean::FunctionItem(build_external_function(cx, did))
72 Res::Def(DefKind::Struct, did) => {
73 record_extern_fqn(cx, did, ItemType::Struct);
74 build_impls(cx, Some(parent_module), did, attrs, &mut ret);
75 clean::StructItem(build_struct(cx, did))
77 Res::Def(DefKind::Union, did) => {
78 record_extern_fqn(cx, did, ItemType::Union);
79 build_impls(cx, Some(parent_module), did, attrs, &mut ret);
80 clean::UnionItem(build_union(cx, did))
82 Res::Def(DefKind::TyAlias, did) => {
83 record_extern_fqn(cx, did, ItemType::Typedef);
84 build_impls(cx, Some(parent_module), did, attrs, &mut ret);
85 clean::TypedefItem(build_type_alias(cx, did))
87 Res::Def(DefKind::Enum, did) => {
88 record_extern_fqn(cx, did, ItemType::Enum);
89 build_impls(cx, Some(parent_module), did, attrs, &mut ret);
90 clean::EnumItem(build_enum(cx, did))
92 Res::Def(DefKind::ForeignTy, did) => {
93 record_extern_fqn(cx, did, ItemType::ForeignType);
94 build_impls(cx, Some(parent_module), did, attrs, &mut ret);
95 clean::ForeignTypeItem
97 // Never inline enum variants but leave them shown as re-exports.
98 Res::Def(DefKind::Variant, _) => return None,
99 // Assume that enum variants and struct types are re-exported next to
100 // their constructors.
101 Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) => return Some(Vec::new()),
102 Res::Def(DefKind::Mod, did) => {
103 record_extern_fqn(cx, did, ItemType::Module);
104 clean::ModuleItem(build_module(cx, did, visited))
106 Res::Def(DefKind::Static(_), did) => {
107 record_extern_fqn(cx, did, ItemType::Static);
108 clean::StaticItem(build_static(cx, did, cx.tcx.is_mutable_static(did)))
110 Res::Def(DefKind::Const, did) => {
111 record_extern_fqn(cx, did, ItemType::Constant);
112 clean::ConstantItem(build_const(cx, did))
114 Res::Def(DefKind::Macro(kind), did) => {
115 let mac = build_macro(cx, did, name, import_def_id);
117 let type_kind = match kind {
118 MacroKind::Bang => ItemType::Macro,
119 MacroKind::Attr => ItemType::ProcAttribute,
120 MacroKind::Derive => ItemType::ProcDerive,
122 record_extern_fqn(cx, did, type_kind);
128 let (attrs, cfg) = merge_attrs(cx, Some(parent_module), load_attrs(cx, did), attrs_clone);
129 cx.inlined.insert(did.into());
130 let mut item = clean::Item::from_def_id_and_attrs_and_parts(
138 if let Some(import_def_id) = import_def_id {
139 // The visibility needs to reflect the one from the reexport and not from the "source" DefId.
140 item.visibility = clean_visibility(cx.tcx.visibility(import_def_id));
146 pub(crate) fn try_inline_glob(
147 cx: &mut DocContext<'_>,
149 visited: &mut FxHashSet<DefId>,
150 inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
151 ) -> Option<Vec<clean::Item>> {
152 let did = res.opt_def_id()?;
158 Res::Def(DefKind::Mod, did) => {
159 let mut items = build_module_items(cx, did, visited, inlined_names);
160 items.drain_filter(|item| {
161 if let Some(name) = item.name {
162 // If an item with the same type and name already exists,
163 // it takes priority over the inlined stuff.
164 !inlined_names.insert((item.type_(), name))
171 // glob imports on things like enums aren't inlined even for local exports, so just bail
176 pub(crate) fn load_attrs<'hir>(cx: &DocContext<'hir>, did: DefId) -> Attrs<'hir> {
177 cx.tcx.get_attrs_unchecked(did)
180 /// Record an external fully qualified name in the external_paths cache.
182 /// These names are used later on by HTML rendering to generate things like
183 /// source links back to the original item.
184 pub(crate) fn record_extern_fqn(cx: &mut DocContext<'_>, did: DefId, kind: ItemType) {
185 let crate_name = cx.tcx.crate_name(did.krate);
188 cx.tcx.def_path(did).data.into_iter().filter_map(|elem| elem.data.get_opt_name());
189 let fqn = if let ItemType::Macro = kind {
190 // Check to see if it is a macro 2.0 or built-in macro
192 CStore::from_tcx(cx.tcx).load_macro_untracked(did, cx.sess()),
193 LoadedMacro::MacroDef(def, _)
194 if matches!(&def.kind, ast::ItemKind::MacroDef(ast_def)
195 if !ast_def.macro_rules)
197 once(crate_name).chain(relative).collect()
199 vec![crate_name, relative.last().expect("relative was empty")]
202 once(crate_name).chain(relative).collect()
206 cx.cache.exact_paths.insert(did, fqn);
208 cx.cache.external_paths.insert(did, (fqn, kind));
212 pub(crate) fn build_external_trait(cx: &mut DocContext<'_>, did: DefId) -> clean::Trait {
215 .associated_items(did)
216 .in_definition_order()
218 // When building an external trait, the cleaned trait will have all items public,
219 // which causes methods to have a `pub` prefix, which is invalid since items in traits
220 // can not have a visibility prefix. Thus we override the visibility here manually.
221 // See https://github.com/rust-lang/rust/issues/81274
222 clean::Item { visibility: Visibility::Inherited, ..clean_middle_assoc_item(item, cx) }
226 let predicates = cx.tcx.predicates_of(did);
227 let generics = clean_ty_generics(cx, cx.tcx.generics_of(did), predicates);
228 let generics = filter_non_trait_generics(did, generics);
229 let (generics, supertrait_bounds) = separate_supertrait_bounds(generics);
230 clean::Trait { def_id: did, generics, items: trait_items, bounds: supertrait_bounds }
233 fn build_external_function<'tcx>(cx: &mut DocContext<'tcx>, did: DefId) -> Box<clean::Function> {
234 let sig = cx.tcx.fn_sig(did);
236 let predicates = cx.tcx.predicates_of(did);
237 let (generics, decl) = clean::enter_impl_trait(cx, |cx| {
238 // NOTE: generics need to be cleaned before the decl!
239 let generics = clean_ty_generics(cx, cx.tcx.generics_of(did), predicates);
240 let decl = clean_fn_decl_from_did_and_sig(cx, Some(did), sig);
243 Box::new(clean::Function { decl, generics })
246 fn build_enum(cx: &mut DocContext<'_>, did: DefId) -> clean::Enum {
247 let predicates = cx.tcx.explicit_predicates_of(did);
250 generics: clean_ty_generics(cx, cx.tcx.generics_of(did), predicates),
251 variants: cx.tcx.adt_def(did).variants().iter().map(|v| clean_variant_def(v, cx)).collect(),
255 fn build_struct(cx: &mut DocContext<'_>, did: DefId) -> clean::Struct {
256 let predicates = cx.tcx.explicit_predicates_of(did);
257 let variant = cx.tcx.adt_def(did).non_enum_variant();
260 struct_type: variant.ctor_kind,
261 generics: clean_ty_generics(cx, cx.tcx.generics_of(did), predicates),
262 fields: variant.fields.iter().map(|x| clean_middle_field(x, cx)).collect(),
266 fn build_union(cx: &mut DocContext<'_>, did: DefId) -> clean::Union {
267 let predicates = cx.tcx.explicit_predicates_of(did);
268 let variant = cx.tcx.adt_def(did).non_enum_variant();
270 let generics = clean_ty_generics(cx, cx.tcx.generics_of(did), predicates);
271 let fields = variant.fields.iter().map(|x| clean_middle_field(x, cx)).collect();
272 clean::Union { generics, fields }
275 fn build_type_alias(cx: &mut DocContext<'_>, did: DefId) -> Box<clean::Typedef> {
276 let predicates = cx.tcx.explicit_predicates_of(did);
277 let type_ = clean_middle_ty(cx.tcx.type_of(did), cx, Some(did));
279 Box::new(clean::Typedef {
281 generics: clean_ty_generics(cx, cx.tcx.generics_of(did), predicates),
286 /// Builds all inherent implementations of an ADT (struct/union/enum) or Trait item/path/reexport.
287 pub(crate) fn build_impls(
288 cx: &mut DocContext<'_>,
289 parent_module: Option<DefId>,
291 attrs: Option<Attrs<'_>>,
292 ret: &mut Vec<clean::Item>,
294 let _prof_timer = cx.tcx.sess.prof.generic_activity("build_inherent_impls");
297 // for each implementation of an item represented by `did`, build the clean::Item for that impl
298 for &did in tcx.inherent_impls(did).iter() {
299 build_impl(cx, parent_module, did, attrs, ret);
303 /// `parent_module` refers to the parent of the re-export, not the original item
304 pub(crate) fn merge_attrs(
305 cx: &mut DocContext<'_>,
306 parent_module: Option<DefId>,
307 old_attrs: Attrs<'_>,
308 new_attrs: Option<Attrs<'_>>,
309 ) -> (clean::Attributes, Option<Arc<clean::cfg::Cfg>>) {
310 // NOTE: If we have additional attributes (from a re-export),
311 // always insert them first. This ensure that re-export
312 // doc comments show up before the original doc comments
313 // when we render them.
314 if let Some(inner) = new_attrs {
315 let mut both = inner.to_vec();
316 both.extend_from_slice(old_attrs);
318 if let Some(new_id) = parent_module {
319 Attributes::from_ast_with_additional(old_attrs, (inner, new_id))
321 Attributes::from_ast(&both)
323 both.cfg(cx.tcx, &cx.cache.hidden_cfg),
326 (Attributes::from_ast(&old_attrs), old_attrs.cfg(cx.tcx, &cx.cache.hidden_cfg))
330 /// Inline an `impl`, inherent or of a trait. The `did` must be for an `impl`.
331 pub(crate) fn build_impl(
332 cx: &mut DocContext<'_>,
333 parent_module: Option<DefId>,
335 attrs: Option<Attrs<'_>>,
336 ret: &mut Vec<clean::Item>,
338 if !cx.inlined.insert(did.into()) {
342 let _prof_timer = cx.tcx.sess.prof.generic_activity("build_impl");
345 let associated_trait = tcx.impl_trait_ref(did);
347 // Only inline impl if the implemented trait is
348 // reachable in rustdoc generated documentation
350 if let Some(traitref) = associated_trait {
351 let did = traitref.def_id;
352 if !cx.cache.access_levels.is_public(did) {
356 if let Some(stab) = tcx.lookup_stability(did) {
357 if stab.is_unstable() && stab.feature == sym::rustc_private {
364 let impl_item = match did.as_local() {
365 Some(did) => match &tcx.hir().expect_item(did).kind {
366 hir::ItemKind::Impl(impl_) => Some(impl_),
367 _ => panic!("`DefID` passed to `build_impl` is not an `impl"),
372 let for_ = match &impl_item {
373 Some(impl_) => clean_ty(impl_.self_ty, cx),
374 None => clean_middle_ty(tcx.type_of(did), cx, Some(did)),
377 // Only inline impl if the implementing type is
378 // reachable in rustdoc generated documentation
380 if let Some(did) = for_.def_id(&cx.cache) {
381 if !cx.cache.access_levels.is_public(did) {
385 if let Some(stab) = tcx.lookup_stability(did) {
386 if stab.is_unstable() && stab.feature == sym::rustc_private {
393 let document_hidden = cx.render_options.document_hidden;
394 let predicates = tcx.explicit_predicates_of(did);
395 let (trait_items, generics) = match impl_item {
400 .map(|item| tcx.hir().impl_item(item.id))
402 // Filter out impl items whose corresponding trait item has `doc(hidden)`
403 // not to document such impl items.
404 // For inherent impls, we don't do any filtering, because that's already done in strip_hidden.rs.
406 // When `--document-hidden-items` is passed, we don't
407 // do any filtering, too.
411 if let Some(associated_trait) = associated_trait {
412 let assoc_kind = match item.kind {
413 hir::ImplItemKind::Const(..) => ty::AssocKind::Const,
414 hir::ImplItemKind::Fn(..) => ty::AssocKind::Fn,
415 hir::ImplItemKind::TyAlias(..) => ty::AssocKind::Type,
418 .associated_items(associated_trait.def_id)
419 .find_by_name_and_kind(
423 associated_trait.def_id,
425 .unwrap(); // SAFETY: For all impl items there exists trait item that has the same name.
426 !tcx.is_doc_hidden(trait_item.def_id)
431 .map(|item| clean_impl_item(item, cx))
432 .collect::<Vec<_>>(),
433 clean_generics(impl_.generics, cx),
436 tcx.associated_items(did)
437 .in_definition_order()
439 // If this is a trait impl, filter out associated items whose corresponding item
440 // in the associated trait is marked `doc(hidden)`.
441 // If this is an inherent impl, filter out private associated items.
442 if let Some(associated_trait) = associated_trait {
444 .associated_items(associated_trait.def_id)
445 .find_by_name_and_kind(
449 associated_trait.def_id,
451 .unwrap(); // corresponding associated item has to exist
452 !tcx.is_doc_hidden(trait_item.def_id)
454 item.visibility(tcx).is_public()
457 .map(|item| clean_middle_assoc_item(item, cx))
458 .collect::<Vec<_>>(),
459 clean::enter_impl_trait(cx, |cx| {
460 clean_ty_generics(cx, tcx.generics_of(did), predicates)
464 let polarity = tcx.impl_polarity(did);
465 let trait_ = associated_trait.map(|t| clean_trait_ref_with_bindings(cx, t, ThinVec::new()));
466 if trait_.as_ref().map(|t| t.def_id()) == tcx.lang_items().deref_trait() {
467 super::build_deref_target_impls(cx, &trait_items, ret);
470 // Return if the trait itself or any types of the generic parameters are doc(hidden).
471 let mut stack: Vec<&Type> = vec![&for_];
473 if let Some(did) = trait_.as_ref().map(|t| t.def_id()) {
474 if tcx.is_doc_hidden(did) {
478 if let Some(generics) = trait_.as_ref().and_then(|t| t.generics()) {
479 stack.extend(generics);
482 while let Some(ty) = stack.pop() {
483 if let Some(did) = ty.def_id(&cx.cache) {
484 if tcx.is_doc_hidden(did) {
488 if let Some(generics) = ty.generics() {
489 stack.extend(generics);
493 if let Some(did) = trait_.as_ref().map(|t| t.def_id()) {
494 record_extern_trait(cx, did);
497 let (merged_attrs, cfg) = merge_attrs(cx, parent_module, load_attrs(cx, did), attrs);
498 trace!("merged_attrs={:?}", merged_attrs);
501 "build_impl: impl {:?} for {:?}",
502 trait_.as_ref().map(|t| t.def_id()),
503 for_.def_id(&cx.cache)
505 ret.push(clean::Item::from_def_id_and_attrs_and_parts(
508 clean::ImplItem(Box::new(clean::Impl {
509 unsafety: hir::Unsafety::Normal,
515 kind: if utils::has_doc_flag(tcx, did, sym::fake_variadic) {
516 ImplKind::FakeVaradic
521 Box::new(merged_attrs),
528 cx: &mut DocContext<'_>,
530 visited: &mut FxHashSet<DefId>,
532 let items = build_module_items(cx, did, visited, &mut FxHashSet::default());
534 let span = clean::Span::new(cx.tcx.def_span(did));
535 clean::Module { items, span }
538 fn build_module_items(
539 cx: &mut DocContext<'_>,
541 visited: &mut FxHashSet<DefId>,
542 inlined_names: &mut FxHashSet<(ItemType, Symbol)>,
543 ) -> Vec<clean::Item> {
544 let mut items = Vec::new();
546 // If we're re-exporting a re-export it may actually re-export something in
547 // two namespaces, so the target may be listed twice. Make sure we only
548 // visit each node at most once.
549 for &item in cx.tcx.module_children(did).iter() {
550 if item.vis.is_public() {
551 let res = item.res.expect_non_local();
552 if let Some(def_id) = res.mod_def_id() {
553 // If we're inlining a glob import, it's possible to have
554 // two distinct modules with the same name. We don't want to
555 // inline it, or mark any of its contents as visited.
557 || inlined_names.contains(&(ItemType::Module, item.ident.name))
558 || !visited.insert(def_id)
563 if let Res::PrimTy(p) = res {
564 // Primitive types can't be inlined so generate an import instead.
565 let prim_ty = clean::PrimitiveType::from(p);
566 items.push(clean::Item {
568 attrs: Box::new(clean::Attributes::default()),
569 item_id: ItemId::Primitive(prim_ty, did.krate),
570 visibility: clean::Public,
571 kind: Box::new(clean::ImportItem(clean::Import::new_simple(
573 clean::ImportSource {
576 segments: vec![clean::PathSegment {
577 name: prim_ty.as_sym(),
578 args: clean::GenericArgs::AngleBracketed {
579 args: Default::default(),
580 bindings: ThinVec::new(),
590 } else if let Some(i) = try_inline(cx, did, None, res, item.ident.name, None, visited) {
599 pub(crate) fn print_inlined_const(tcx: TyCtxt<'_>, did: DefId) -> String {
600 if let Some(did) = did.as_local() {
601 let hir_id = tcx.hir().local_def_id_to_hir_id(did);
602 rustc_hir_pretty::id_to_string(&tcx.hir(), hir_id)
604 tcx.rendered_const(did).clone()
608 fn build_const(cx: &mut DocContext<'_>, def_id: DefId) -> clean::Constant {
610 type_: clean_middle_ty(cx.tcx.type_of(def_id), cx, Some(def_id)),
611 kind: clean::ConstantKind::Extern { def_id },
615 fn build_static(cx: &mut DocContext<'_>, did: DefId, mutable: bool) -> clean::Static {
617 type_: clean_middle_ty(cx.tcx.type_of(did), cx, Some(did)),
618 mutability: if mutable { Mutability::Mut } else { Mutability::Not },
624 cx: &mut DocContext<'_>,
627 import_def_id: Option<DefId>,
628 ) -> clean::ItemKind {
629 match CStore::from_tcx(cx.tcx).load_macro_untracked(def_id, cx.sess()) {
630 LoadedMacro::MacroDef(item_def, _) => {
631 if let ast::ItemKind::MacroDef(ref def) = item_def.kind {
632 let vis = clean_visibility(cx.tcx.visibility(import_def_id.unwrap_or(def_id)));
633 clean::MacroItem(clean::Macro {
634 source: utils::display_macro_source(cx, name, def, def_id, vis),
640 LoadedMacro::ProcMacro(ext) => clean::ProcMacroItem(clean::ProcMacro {
641 kind: ext.macro_kind(),
642 helpers: ext.helper_attrs,
647 /// A trait's generics clause actually contains all of the predicates for all of
648 /// its associated types as well. We specifically move these clauses to the
649 /// associated types instead when displaying, so when we're generating the
650 /// generics for the trait itself we need to be sure to remove them.
651 /// We also need to remove the implied "recursive" Self: Trait bound.
653 /// The inverse of this filtering logic can be found in the `Clean`
654 /// implementation for `AssociatedType`
655 fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean::Generics {
656 for pred in &mut g.where_predicates {
658 clean::WherePredicate::BoundPredicate {
659 ty: clean::Generic(ref s),
662 } if *s == kw::SelfUpper => {
663 bounds.retain(|bound| match bound {
664 clean::GenericBound::TraitBound(clean::PolyTrait { trait_, .. }, _) => {
665 trait_.def_id() != trait_did
674 g.where_predicates.retain(|pred| match pred {
675 clean::WherePredicate::BoundPredicate {
676 ty: clean::QPath(box clean::QPathData { self_type: clean::Generic(ref s), trait_, .. }),
679 } => !(bounds.is_empty() || *s == kw::SelfUpper && trait_.def_id() == trait_did),
685 /// Supertrait bounds for a trait are also listed in the generics coming from
686 /// the metadata for a crate, so we want to separate those out and create a new
687 /// list of explicit supertrait bounds to render nicely.
688 fn separate_supertrait_bounds(
689 mut g: clean::Generics,
690 ) -> (clean::Generics, Vec<clean::GenericBound>) {
691 let mut ty_bounds = Vec::new();
692 g.where_predicates.retain(|pred| match *pred {
693 clean::WherePredicate::BoundPredicate { ty: clean::Generic(ref s), ref bounds, .. }
694 if *s == kw::SelfUpper =>
696 ty_bounds.extend(bounds.iter().cloned());
704 pub(crate) fn record_extern_trait(cx: &mut DocContext<'_>, did: DefId) {
710 if cx.external_traits.borrow().contains_key(&did) || cx.active_extern_traits.contains(&did)
717 cx.active_extern_traits.insert(did);
720 debug!("record_extern_trait: {:?}", did);
721 let trait_ = build_external_trait(cx, did);
723 let trait_ = clean::TraitWithExtraInfo {
725 is_notable: clean::utils::has_doc_flag(cx.tcx, did, sym::notable_trait),
727 cx.external_traits.borrow_mut().insert(did, trait_);
728 cx.active_extern_traits.remove(&did);