1 //! Support for inlining external documentation into the current AST.
7 use rustc_data_structures::fx::FxHashSet;
9 use rustc_hir::def::{DefKind, Res};
10 use rustc_hir::def_id::DefId;
11 use rustc_hir::Mutability;
12 use rustc_metadata::creader::{CStore, LoadedMacro};
13 use rustc_middle::ty::{self, TyCtxt};
14 use rustc_span::hygiene::MacroKind;
15 use rustc_span::symbol::{kw, sym, Symbol};
18 self, utils, Attributes, AttributesExt, GetDefId, ItemId, NestedAttributesExt, Type,
20 use crate::core::DocContext;
21 use crate::formats::item_type::ItemType;
23 use super::{Clean, Visibility};
25 type Attrs<'hir> = rustc_middle::ty::Attributes<'hir>;
27 /// Attempt to inline a definition into this AST.
29 /// This function will fetch the definition specified, and if it is
30 /// from another crate it will attempt to inline the documentation
31 /// from the other crate into this crate.
33 /// This is primarily used for `pub use` statements which are, in general,
34 /// implementation details. Inlining the documentation should help provide a
35 /// better experience when reading the documentation in this use case.
37 /// The returned value is `None` if the definition could not be inlined,
38 /// and `Some` of a vector of items if it was successfully expanded.
40 /// `parent_module` refers to the parent of the *re-export*, not the original item.
42 cx: &mut DocContext<'_>,
44 import_def_id: Option<DefId>,
47 attrs: Option<Attrs<'_>>,
48 visited: &mut FxHashSet<DefId>,
49 ) -> Option<Vec<clean::Item>> {
50 let did = res.opt_def_id()?;
54 let mut ret = Vec::new();
56 debug!("attrs={:?}", attrs);
57 let attrs_clone = attrs;
59 let kind = match res {
60 Res::Def(DefKind::Trait, did) => {
61 record_extern_fqn(cx, did, ItemType::Trait);
62 build_impls(cx, Some(parent_module), did, attrs, &mut ret);
63 clean::TraitItem(build_external_trait(cx, did))
65 Res::Def(DefKind::Fn, did) => {
66 record_extern_fqn(cx, did, ItemType::Function);
67 clean::FunctionItem(build_external_function(cx, did))
69 Res::Def(DefKind::Struct, did) => {
70 record_extern_fqn(cx, did, ItemType::Struct);
71 build_impls(cx, Some(parent_module), did, attrs, &mut ret);
72 clean::StructItem(build_struct(cx, did))
74 Res::Def(DefKind::Union, did) => {
75 record_extern_fqn(cx, did, ItemType::Union);
76 build_impls(cx, Some(parent_module), did, attrs, &mut ret);
77 clean::UnionItem(build_union(cx, did))
79 Res::Def(DefKind::TyAlias, did) => {
80 record_extern_fqn(cx, did, ItemType::Typedef);
81 build_impls(cx, Some(parent_module), did, attrs, &mut ret);
82 clean::TypedefItem(build_type_alias(cx, did), false)
84 Res::Def(DefKind::Enum, did) => {
85 record_extern_fqn(cx, did, ItemType::Enum);
86 build_impls(cx, Some(parent_module), did, attrs, &mut ret);
87 clean::EnumItem(build_enum(cx, did))
89 Res::Def(DefKind::ForeignTy, did) => {
90 record_extern_fqn(cx, did, ItemType::ForeignType);
91 build_impls(cx, Some(parent_module), did, attrs, &mut ret);
92 clean::ForeignTypeItem
94 // Never inline enum variants but leave them shown as re-exports.
95 Res::Def(DefKind::Variant, _) => return None,
96 // Assume that enum variants and struct types are re-exported next to
97 // their constructors.
98 Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) => return Some(Vec::new()),
99 Res::Def(DefKind::Mod, did) => {
100 record_extern_fqn(cx, did, ItemType::Module);
101 clean::ModuleItem(build_module(cx, did, visited))
103 Res::Def(DefKind::Static, did) => {
104 record_extern_fqn(cx, did, ItemType::Static);
105 clean::StaticItem(build_static(cx, did, cx.tcx.is_mutable_static(did)))
107 Res::Def(DefKind::Const, did) => {
108 record_extern_fqn(cx, did, ItemType::Constant);
109 clean::ConstantItem(build_const(cx, did))
111 Res::Def(DefKind::Macro(kind), did) => {
112 let mac = build_macro(cx, did, name, import_def_id);
114 let type_kind = match kind {
115 MacroKind::Bang => ItemType::Macro,
116 MacroKind::Attr => ItemType::ProcAttribute,
117 MacroKind::Derive => ItemType::ProcDerive,
119 record_extern_fqn(cx, did, type_kind);
125 let (attrs, cfg) = merge_attrs(cx, Some(parent_module), load_attrs(cx, did), attrs_clone);
126 cx.inlined.insert(did.into());
127 let mut item = clean::Item::from_def_id_and_attrs_and_parts(
135 if let Some(import_def_id) = import_def_id {
136 // The visibility needs to reflect the one from the reexport and not from the "source" DefId.
137 item.visibility = cx.tcx.visibility(import_def_id).clean(cx);
143 crate fn try_inline_glob(
144 cx: &mut DocContext<'_>,
146 visited: &mut FxHashSet<DefId>,
147 ) -> Option<Vec<clean::Item>> {
148 let did = res.opt_def_id()?;
154 Res::Def(DefKind::Mod, did) => {
155 let m = build_module(cx, did, visited);
158 // glob imports on things like enums aren't inlined even for local exports, so just bail
163 crate fn load_attrs<'hir>(cx: &DocContext<'hir>, did: DefId) -> Attrs<'hir> {
164 cx.tcx.get_attrs(did)
167 /// Record an external fully qualified name in the external_paths cache.
169 /// These names are used later on by HTML rendering to generate things like
170 /// source links back to the original item.
171 crate fn record_extern_fqn(cx: &mut DocContext<'_>, did: DefId, kind: ItemType) {
172 let crate_name = cx.tcx.crate_name(did.krate).to_string();
174 let relative = cx.tcx.def_path(did).data.into_iter().filter_map(|elem| {
175 // extern blocks have an empty name
176 let s = elem.data.to_string();
177 if !s.is_empty() { Some(s) } else { None }
179 let fqn = if let ItemType::Macro = kind {
180 // Check to see if it is a macro 2.0 or built-in macro
182 CStore::from_tcx(cx.tcx).load_macro_untracked(did, cx.sess()),
183 LoadedMacro::MacroDef(def, _)
184 if matches!(&def.kind, ast::ItemKind::MacroDef(ast_def)
185 if !ast_def.macro_rules)
187 once(crate_name).chain(relative).collect()
189 vec![crate_name, relative.last().expect("relative was empty")]
192 once(crate_name).chain(relative).collect()
196 cx.cache.exact_paths.insert(did, fqn);
198 cx.cache.external_paths.insert(did, (fqn, kind));
202 crate fn build_external_trait(cx: &mut DocContext<'_>, did: DefId) -> clean::Trait {
205 .associated_items(did)
206 .in_definition_order()
208 // When building an external trait, the cleaned trait will have all items public,
209 // which causes methods to have a `pub` prefix, which is invalid since items in traits
210 // can not have a visibility prefix. Thus we override the visibility here manually.
211 // See https://github.com/rust-lang/rust/issues/81274
212 clean::Item { visibility: Visibility::Inherited, ..item.clean(cx) }
216 let predicates = cx.tcx.predicates_of(did);
217 let generics = (cx.tcx.generics_of(did), predicates).clean(cx);
218 let generics = filter_non_trait_generics(did, generics);
219 let (generics, supertrait_bounds) = separate_supertrait_bounds(generics);
220 let is_auto = cx.tcx.trait_is_auto(did);
222 unsafety: cx.tcx.trait_def(did).unsafety,
225 bounds: supertrait_bounds,
230 fn build_external_function(cx: &mut DocContext<'_>, did: DefId) -> clean::Function {
231 let sig = cx.tcx.fn_sig(did);
234 if cx.tcx.is_const_fn_raw(did) { hir::Constness::Const } else { hir::Constness::NotConst };
235 let asyncness = cx.tcx.asyncness(did);
236 let predicates = cx.tcx.predicates_of(did);
237 let (generics, decl) = clean::enter_impl_trait(cx, |cx| {
238 ((cx.tcx.generics_of(did), predicates).clean(cx), (did, sig).clean(cx))
243 header: hir::FnHeader { unsafety: sig.unsafety(), abi: sig.abi(), constness, asyncness },
247 fn build_enum(cx: &mut DocContext<'_>, did: DefId) -> clean::Enum {
248 let predicates = cx.tcx.explicit_predicates_of(did);
251 generics: (cx.tcx.generics_of(did), predicates).clean(cx),
252 variants_stripped: false,
253 variants: cx.tcx.adt_def(did).variants.clean(cx),
257 fn build_struct(cx: &mut DocContext<'_>, did: DefId) -> clean::Struct {
258 let predicates = cx.tcx.explicit_predicates_of(did);
259 let variant = cx.tcx.adt_def(did).non_enum_variant();
262 struct_type: variant.ctor_kind,
263 generics: (cx.tcx.generics_of(did), predicates).clean(cx),
264 fields: variant.fields.clean(cx),
265 fields_stripped: false,
269 fn build_union(cx: &mut DocContext<'_>, did: DefId) -> clean::Union {
270 let predicates = cx.tcx.explicit_predicates_of(did);
271 let variant = cx.tcx.adt_def(did).non_enum_variant();
274 generics: (cx.tcx.generics_of(did), predicates).clean(cx),
275 fields: variant.fields.clean(cx),
276 fields_stripped: false,
280 fn build_type_alias(cx: &mut DocContext<'_>, did: DefId) -> clean::Typedef {
281 let predicates = cx.tcx.explicit_predicates_of(did);
282 let type_ = cx.tcx.type_of(did).clean(cx);
286 generics: (cx.tcx.generics_of(did), predicates).clean(cx),
291 /// Builds all inherent implementations of an ADT (struct/union/enum) or Trait item/path/reexport.
292 crate fn build_impls(
293 cx: &mut DocContext<'_>,
294 parent_module: Option<DefId>,
296 attrs: Option<Attrs<'_>>,
297 ret: &mut Vec<clean::Item>,
301 // for each implementation of an item represented by `did`, build the clean::Item for that impl
302 for &did in tcx.inherent_impls(did).iter() {
303 build_impl(cx, parent_module, did, attrs, ret);
307 /// `parent_module` refers to the parent of the re-export, not the original item
309 cx: &mut DocContext<'_>,
310 parent_module: Option<DefId>,
311 old_attrs: Attrs<'_>,
312 new_attrs: Option<Attrs<'_>>,
313 ) -> (clean::Attributes, Option<Arc<clean::cfg::Cfg>>) {
314 // NOTE: If we have additional attributes (from a re-export),
315 // always insert them first. This ensure that re-export
316 // doc comments show up before the original doc comments
317 // when we render them.
318 if let Some(inner) = new_attrs {
319 let mut both = inner.to_vec();
320 both.extend_from_slice(old_attrs);
322 if let Some(new_id) = parent_module {
323 Attributes::from_ast(old_attrs, Some((inner, new_id)))
325 Attributes::from_ast(&both, None)
330 (old_attrs.clean(cx), old_attrs.cfg(cx.sess()))
334 /// Builds a specific implementation of a type. The `did` could be a type method or trait method.
336 cx: &mut DocContext<'_>,
337 parent_module: impl Into<Option<DefId>>,
339 attrs: Option<Attrs<'_>>,
340 ret: &mut Vec<clean::Item>,
342 if !cx.inlined.insert(did.into()) {
347 let associated_trait = tcx.impl_trait_ref(did);
349 // Only inline impl if the implemented trait is
350 // reachable in rustdoc generated documentation
352 if let Some(traitref) = associated_trait {
353 let did = traitref.def_id;
354 if !cx.cache.access_levels.is_public(did) {
358 if let Some(stab) = tcx.lookup_stability(did) {
359 if stab.level.is_unstable() && stab.feature == sym::rustc_private {
366 let impl_item = match did.as_local() {
368 let hir_id = tcx.hir().local_def_id_to_hir_id(did);
369 match &tcx.hir().expect_item(hir_id).kind {
370 hir::ItemKind::Impl(impl_) => Some(impl_),
371 _ => panic!("`DefID` passed to `build_impl` is not an `impl"),
377 let for_ = match &impl_item {
378 Some(impl_) => impl_.self_ty.clean(cx),
379 None => tcx.type_of(did).clean(cx),
382 // Only inline impl if the implementing type is
383 // reachable in rustdoc generated documentation
385 if let Some(did) = for_.def_id() {
386 if !cx.cache.access_levels.is_public(did) {
390 if let Some(stab) = tcx.lookup_stability(did) {
391 if stab.level.is_unstable() && stab.feature == sym::rustc_private {
398 let predicates = tcx.explicit_predicates_of(did);
399 let (trait_items, generics) = match impl_item {
404 .map(|item| tcx.hir().impl_item(item.id).clean(cx))
405 .collect::<Vec<_>>(),
406 impl_.generics.clean(cx),
409 tcx.associated_items(did)
410 .in_definition_order()
412 if associated_trait.is_some() || item.vis == ty::Visibility::Public {
418 .collect::<Vec<_>>(),
419 clean::enter_impl_trait(cx, |cx| (tcx.generics_of(did), predicates).clean(cx)),
422 let polarity = tcx.impl_polarity(did);
423 let trait_ = associated_trait.clean(cx).map(|bound| match bound {
424 clean::GenericBound::TraitBound(polyt, _) => polyt.trait_,
425 clean::GenericBound::Outlives(..) => unreachable!(),
427 if trait_.def_id() == tcx.lang_items().deref_trait() {
428 super::build_deref_target_impls(cx, &trait_items, ret);
431 // Return if the trait itself or any types of the generic parameters are doc(hidden).
432 let mut stack: Vec<&Type> = trait_.iter().collect();
434 while let Some(ty) = stack.pop() {
435 if let Some(did) = ty.def_id() {
436 if cx.tcx.get_attrs(did).lists(sym::doc).has_word(sym::hidden) {
440 if let Some(generics) = ty.generics() {
441 stack.extend(generics);
445 if let Some(trait_did) = trait_.def_id() {
446 record_extern_trait(cx, trait_did);
449 let (merged_attrs, cfg) = merge_attrs(cx, parent_module.into(), load_attrs(cx, did), attrs);
450 trace!("merged_attrs={:?}", merged_attrs);
452 trace!("build_impl: impl {:?} for {:?}", trait_.def_id(), for_.def_id());
453 ret.push(clean::Item::from_def_id_and_attrs_and_parts(
456 clean::ImplItem(clean::Impl {
457 span: clean::types::rustc_span(did, cx.tcx),
458 unsafety: hir::Unsafety::Normal,
463 negative_polarity: polarity.clean(cx),
467 Box::new(merged_attrs),
474 cx: &mut DocContext<'_>,
476 visited: &mut FxHashSet<DefId>,
478 let mut items = Vec::new();
480 // If we're re-exporting a re-export it may actually re-export something in
481 // two namespaces, so the target may be listed twice. Make sure we only
482 // visit each node at most once.
483 for &item in cx.tcx.item_children(did).iter() {
484 if item.vis == ty::Visibility::Public {
485 let res = item.res.expect_non_local();
486 if let Some(def_id) = res.mod_def_id() {
487 if did == def_id || !visited.insert(def_id) {
491 if let Res::PrimTy(p) = res {
492 // Primitive types can't be inlined so generate an import instead.
493 let prim_ty = clean::PrimitiveType::from(p);
494 items.push(clean::Item {
496 attrs: Box::new(clean::Attributes::default()),
497 def_id: ItemId::Primitive(prim_ty, did.krate),
498 visibility: clean::Public,
499 kind: Box::new(clean::ImportItem(clean::Import::new_simple(
501 clean::ImportSource {
505 segments: vec![clean::PathSegment {
506 name: prim_ty.as_sym(),
507 args: clean::GenericArgs::AngleBracketed {
509 bindings: Vec::new(),
519 } else if let Some(i) = try_inline(cx, did, None, res, item.ident.name, None, visited) {
525 let span = clean::Span::new(cx.tcx.def_span(did));
526 clean::Module { items, span }
529 crate fn print_inlined_const(tcx: TyCtxt<'_>, did: DefId) -> String {
530 if let Some(did) = did.as_local() {
531 let hir_id = tcx.hir().local_def_id_to_hir_id(did);
532 rustc_hir_pretty::id_to_string(&tcx.hir(), hir_id)
534 tcx.rendered_const(did)
538 fn build_const(cx: &mut DocContext<'_>, def_id: DefId) -> clean::Constant {
540 type_: cx.tcx.type_of(def_id).clean(cx),
541 kind: clean::ConstantKind::Extern { def_id },
545 fn build_static(cx: &mut DocContext<'_>, did: DefId, mutable: bool) -> clean::Static {
547 type_: cx.tcx.type_of(did).clean(cx),
548 mutability: if mutable { Mutability::Mut } else { Mutability::Not },
554 cx: &mut DocContext<'_>,
557 import_def_id: Option<DefId>,
558 ) -> clean::ItemKind {
559 match CStore::from_tcx(cx.tcx).load_macro_untracked(def_id, cx.sess()) {
560 LoadedMacro::MacroDef(item_def, _) => {
561 if let ast::ItemKind::MacroDef(ref def) = item_def.kind {
562 clean::MacroItem(clean::Macro {
563 source: utils::display_macro_source(
568 cx.tcx.visibility(import_def_id.unwrap_or(def_id)),
575 LoadedMacro::ProcMacro(ext) => clean::ProcMacroItem(clean::ProcMacro {
576 kind: ext.macro_kind(),
577 helpers: ext.helper_attrs,
582 /// A trait's generics clause actually contains all of the predicates for all of
583 /// its associated types as well. We specifically move these clauses to the
584 /// associated types instead when displaying, so when we're generating the
585 /// generics for the trait itself we need to be sure to remove them.
586 /// We also need to remove the implied "recursive" Self: Trait bound.
588 /// The inverse of this filtering logic can be found in the `Clean`
589 /// implementation for `AssociatedType`
590 fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean::Generics {
591 for pred in &mut g.where_predicates {
593 clean::WherePredicate::BoundPredicate {
594 ty: clean::Generic(ref s),
597 } if *s == kw::SelfUpper => {
598 bounds.retain(|bound| match *bound {
599 clean::GenericBound::TraitBound(
600 clean::PolyTrait { trait_: clean::ResolvedPath { did, .. }, .. },
602 ) => did != trait_did,
610 g.where_predicates.retain(|pred| match *pred {
611 clean::WherePredicate::BoundPredicate {
614 self_type: box clean::Generic(ref s),
615 trait_: box clean::ResolvedPath { did, .. },
621 } => !(bounds.is_empty() || *s == kw::SelfUpper && did == trait_did),
627 /// Supertrait bounds for a trait are also listed in the generics coming from
628 /// the metadata for a crate, so we want to separate those out and create a new
629 /// list of explicit supertrait bounds to render nicely.
630 fn separate_supertrait_bounds(
631 mut g: clean::Generics,
632 ) -> (clean::Generics, Vec<clean::GenericBound>) {
633 let mut ty_bounds = Vec::new();
634 g.where_predicates.retain(|pred| match *pred {
635 clean::WherePredicate::BoundPredicate { ty: clean::Generic(ref s), ref bounds, .. }
636 if *s == kw::SelfUpper =>
638 ty_bounds.extend(bounds.iter().cloned());
646 crate fn record_extern_trait(cx: &mut DocContext<'_>, did: DefId) {
652 if cx.external_traits.borrow().contains_key(&did) || cx.active_extern_traits.contains(&did)
659 cx.active_extern_traits.insert(did);
662 debug!("record_extern_trait: {:?}", did);
663 let trait_ = build_external_trait(cx, did);
665 let trait_ = clean::TraitWithExtraInfo {
667 is_notable: clean::utils::has_doc_flag(cx.tcx.get_attrs(did), sym::notable_trait),
669 cx.external_traits.borrow_mut().insert(did, trait_);
670 cx.active_extern_traits.remove(&did);