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};
17 use crate::clean::{self, utils, Attributes, AttributesExt, ItemId, NestedAttributesExt, Type};
18 use crate::core::DocContext;
19 use crate::formats::item_type::ItemType;
21 use super::{Clean, Visibility};
23 type Attrs<'hir> = rustc_middle::ty::Attributes<'hir>;
25 /// Attempt to inline a definition into this AST.
27 /// This function will fetch the definition specified, and if it is
28 /// from another crate it will attempt to inline the documentation
29 /// from the other crate into this crate.
31 /// This is primarily used for `pub use` statements which are, in general,
32 /// implementation details. Inlining the documentation should help provide a
33 /// better experience when reading the documentation in this use case.
35 /// The returned value is `None` if the definition could not be inlined,
36 /// and `Some` of a vector of items if it was successfully expanded.
38 /// `parent_module` refers to the parent of the *re-export*, not the original item.
40 cx: &mut DocContext<'_>,
42 import_def_id: Option<DefId>,
45 attrs: Option<Attrs<'_>>,
46 visited: &mut FxHashSet<DefId>,
47 ) -> Option<Vec<clean::Item>> {
48 let did = res.opt_def_id()?;
52 let mut ret = Vec::new();
54 debug!("attrs={:?}", attrs);
55 let attrs_clone = attrs;
57 let kind = match res {
58 Res::Def(DefKind::Trait, did) => {
59 record_extern_fqn(cx, did, ItemType::Trait);
60 build_impls(cx, Some(parent_module), did, attrs, &mut ret);
61 clean::TraitItem(build_external_trait(cx, did))
63 Res::Def(DefKind::Fn, did) => {
64 record_extern_fqn(cx, did, ItemType::Function);
65 clean::FunctionItem(build_external_function(cx, did))
67 Res::Def(DefKind::Struct, did) => {
68 record_extern_fqn(cx, did, ItemType::Struct);
69 build_impls(cx, Some(parent_module), did, attrs, &mut ret);
70 clean::StructItem(build_struct(cx, did))
72 Res::Def(DefKind::Union, did) => {
73 record_extern_fqn(cx, did, ItemType::Union);
74 build_impls(cx, Some(parent_module), did, attrs, &mut ret);
75 clean::UnionItem(build_union(cx, did))
77 Res::Def(DefKind::TyAlias, did) => {
78 record_extern_fqn(cx, did, ItemType::Typedef);
79 build_impls(cx, Some(parent_module), did, attrs, &mut ret);
80 clean::TypedefItem(build_type_alias(cx, did), false)
82 Res::Def(DefKind::Enum, did) => {
83 record_extern_fqn(cx, did, ItemType::Enum);
84 build_impls(cx, Some(parent_module), did, attrs, &mut ret);
85 clean::EnumItem(build_enum(cx, did))
87 Res::Def(DefKind::ForeignTy, did) => {
88 record_extern_fqn(cx, did, ItemType::ForeignType);
89 build_impls(cx, Some(parent_module), did, attrs, &mut ret);
90 clean::ForeignTypeItem
92 // Never inline enum variants but leave them shown as re-exports.
93 Res::Def(DefKind::Variant, _) => return None,
94 // Assume that enum variants and struct types are re-exported next to
95 // their constructors.
96 Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) => return Some(Vec::new()),
97 Res::Def(DefKind::Mod, did) => {
98 record_extern_fqn(cx, did, ItemType::Module);
99 clean::ModuleItem(build_module(cx, did, visited))
101 Res::Def(DefKind::Static, did) => {
102 record_extern_fqn(cx, did, ItemType::Static);
103 clean::StaticItem(build_static(cx, did, cx.tcx.is_mutable_static(did)))
105 Res::Def(DefKind::Const, did) => {
106 record_extern_fqn(cx, did, ItemType::Constant);
107 clean::ConstantItem(build_const(cx, did))
109 Res::Def(DefKind::Macro(kind), did) => {
110 let mac = build_macro(cx, did, name, import_def_id);
112 let type_kind = match kind {
113 MacroKind::Bang => ItemType::Macro,
114 MacroKind::Attr => ItemType::ProcAttribute,
115 MacroKind::Derive => ItemType::ProcDerive,
117 record_extern_fqn(cx, did, type_kind);
123 let (attrs, cfg) = merge_attrs(cx, Some(parent_module), load_attrs(cx, did), attrs_clone);
124 cx.inlined.insert(did.into());
126 clean::Item::from_def_id_and_attrs_and_parts(did, Some(name), kind, box attrs, cx, cfg);
127 if let Some(import_def_id) = import_def_id {
128 // The visibility needs to reflect the one from the reexport and not from the "source" DefId.
129 item.visibility = cx.tcx.visibility(import_def_id).clean(cx);
135 crate fn try_inline_glob(
136 cx: &mut DocContext<'_>,
138 visited: &mut FxHashSet<DefId>,
139 ) -> Option<Vec<clean::Item>> {
140 let did = res.opt_def_id()?;
146 Res::Def(DefKind::Mod, did) => {
147 let m = build_module(cx, did, visited);
150 // glob imports on things like enums aren't inlined even for local exports, so just bail
155 crate fn load_attrs<'hir>(cx: &DocContext<'hir>, did: DefId) -> Attrs<'hir> {
156 cx.tcx.get_attrs(did)
159 /// Record an external fully qualified name in the external_paths cache.
161 /// These names are used later on by HTML rendering to generate things like
162 /// source links back to the original item.
163 crate fn record_extern_fqn(cx: &mut DocContext<'_>, did: DefId, kind: ItemType) {
164 let crate_name = cx.tcx.crate_name(did.krate).to_string();
166 let relative = cx.tcx.def_path(did).data.into_iter().filter_map(|elem| {
167 // extern blocks have an empty name
168 let s = elem.data.to_string();
169 if !s.is_empty() { Some(s) } else { None }
171 let fqn = if let ItemType::Macro = kind {
172 // Check to see if it is a macro 2.0 or built-in macro
174 CStore::from_tcx(cx.tcx).load_macro_untracked(did, cx.sess()),
175 LoadedMacro::MacroDef(def, _)
176 if matches!(&def.kind, ast::ItemKind::MacroDef(ast_def)
177 if !ast_def.macro_rules)
179 once(crate_name).chain(relative).collect()
181 vec![crate_name, relative.last().expect("relative was empty")]
184 once(crate_name).chain(relative).collect()
188 cx.cache.exact_paths.insert(did, fqn);
190 cx.cache.external_paths.insert(did, (fqn, kind));
194 crate fn build_external_trait(cx: &mut DocContext<'_>, did: DefId) -> clean::Trait {
197 .associated_items(did)
198 .in_definition_order()
200 // When building an external trait, the cleaned trait will have all items public,
201 // which causes methods to have a `pub` prefix, which is invalid since items in traits
202 // can not have a visibility prefix. Thus we override the visibility here manually.
203 // See https://github.com/rust-lang/rust/issues/81274
204 clean::Item { visibility: Visibility::Inherited, ..item.clean(cx) }
208 let predicates = cx.tcx.predicates_of(did);
209 let generics = (cx.tcx.generics_of(did), predicates).clean(cx);
210 let generics = filter_non_trait_generics(did, generics);
211 let (generics, supertrait_bounds) = separate_supertrait_bounds(generics);
212 let is_auto = cx.tcx.trait_is_auto(did);
214 unsafety: cx.tcx.trait_def(did).unsafety,
217 bounds: supertrait_bounds,
222 fn build_external_function(cx: &mut DocContext<'_>, did: DefId) -> clean::Function {
223 let sig = cx.tcx.fn_sig(did);
226 if cx.tcx.is_const_fn_raw(did) { hir::Constness::Const } else { hir::Constness::NotConst };
227 let asyncness = cx.tcx.asyncness(did);
228 let predicates = cx.tcx.predicates_of(did);
229 let (generics, decl) = clean::enter_impl_trait(cx, |cx| {
230 ((cx.tcx.generics_of(did), predicates).clean(cx), (did, sig).clean(cx))
235 header: hir::FnHeader { unsafety: sig.unsafety(), abi: sig.abi(), constness, asyncness },
239 fn build_enum(cx: &mut DocContext<'_>, did: DefId) -> clean::Enum {
240 let predicates = cx.tcx.explicit_predicates_of(did);
243 generics: (cx.tcx.generics_of(did), predicates).clean(cx),
244 variants_stripped: false,
245 variants: cx.tcx.adt_def(did).variants.clean(cx),
249 fn build_struct(cx: &mut DocContext<'_>, did: DefId) -> clean::Struct {
250 let predicates = cx.tcx.explicit_predicates_of(did);
251 let variant = cx.tcx.adt_def(did).non_enum_variant();
254 struct_type: variant.ctor_kind,
255 generics: (cx.tcx.generics_of(did), predicates).clean(cx),
256 fields: variant.fields.clean(cx),
257 fields_stripped: false,
261 fn build_union(cx: &mut DocContext<'_>, did: DefId) -> clean::Union {
262 let predicates = cx.tcx.explicit_predicates_of(did);
263 let variant = cx.tcx.adt_def(did).non_enum_variant();
266 generics: (cx.tcx.generics_of(did), predicates).clean(cx),
267 fields: variant.fields.clean(cx),
268 fields_stripped: false,
272 fn build_type_alias(cx: &mut DocContext<'_>, did: DefId) -> clean::Typedef {
273 let predicates = cx.tcx.explicit_predicates_of(did);
274 let type_ = cx.tcx.type_of(did).clean(cx);
278 generics: (cx.tcx.generics_of(did), predicates).clean(cx),
283 /// Builds all inherent implementations of an ADT (struct/union/enum) or Trait item/path/reexport.
284 crate fn build_impls(
285 cx: &mut DocContext<'_>,
286 parent_module: Option<DefId>,
288 attrs: Option<Attrs<'_>>,
289 ret: &mut Vec<clean::Item>,
293 // for each implementation of an item represented by `did`, build the clean::Item for that impl
294 for &did in tcx.inherent_impls(did).iter() {
295 build_impl(cx, parent_module, did, attrs, ret);
299 /// `parent_module` refers to the parent of the re-export, not the original item
301 cx: &mut DocContext<'_>,
302 parent_module: Option<DefId>,
303 old_attrs: Attrs<'_>,
304 new_attrs: Option<Attrs<'_>>,
305 ) -> (clean::Attributes, Option<Arc<clean::cfg::Cfg>>) {
306 // NOTE: If we have additional attributes (from a re-export),
307 // always insert them first. This ensure that re-export
308 // doc comments show up before the original doc comments
309 // when we render them.
310 if let Some(inner) = new_attrs {
311 let mut both = inner.to_vec();
312 both.extend_from_slice(old_attrs);
314 if let Some(new_id) = parent_module {
315 Attributes::from_ast(old_attrs, Some((inner, new_id)))
317 Attributes::from_ast(&both, None)
319 both.cfg(cx.tcx, &cx.cache.hidden_cfg),
322 (old_attrs.clean(cx), old_attrs.cfg(cx.tcx, &cx.cache.hidden_cfg))
326 /// Inline an `impl`, inherent or of a trait. The `did` must be for an `impl`.
328 cx: &mut DocContext<'_>,
329 parent_module: impl Into<Option<DefId>>,
331 attrs: Option<Attrs<'_>>,
332 ret: &mut Vec<clean::Item>,
334 if !cx.inlined.insert(did.into()) {
338 let _prof_timer = cx.tcx.sess.prof.generic_activity("build_extern_trait_impl");
341 let associated_trait = tcx.impl_trait_ref(did);
343 // Only inline impl if the implemented trait is
344 // reachable in rustdoc generated documentation
346 if let Some(traitref) = associated_trait {
347 let did = traitref.def_id;
348 if !cx.cache.access_levels.is_public(did) {
352 if let Some(stab) = tcx.lookup_stability(did) {
353 if stab.level.is_unstable() && stab.feature == sym::rustc_private {
360 let impl_item = match did.as_local() {
362 let hir_id = tcx.hir().local_def_id_to_hir_id(did);
363 match &tcx.hir().expect_item(hir_id).kind {
364 hir::ItemKind::Impl(impl_) => Some(impl_),
365 _ => panic!("`DefID` passed to `build_impl` is not an `impl"),
371 let for_ = match &impl_item {
372 Some(impl_) => impl_.self_ty.clean(cx),
373 None => tcx.type_of(did).clean(cx),
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.level.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.get_attrs(trait_item.def_id).lists(sym::doc).has_word(sym::hidden)
430 .map(|item| item.clean(cx))
431 .collect::<Vec<_>>(),
432 impl_.generics.clean(cx),
435 tcx.associated_items(did)
436 .in_definition_order()
438 if associated_trait.is_some() || item.vis == ty::Visibility::Public {
444 .collect::<Vec<_>>(),
445 clean::enter_impl_trait(cx, |cx| (tcx.generics_of(did), predicates).clean(cx)),
448 let polarity = tcx.impl_polarity(did);
449 let trait_ = associated_trait.clean(cx);
450 if trait_.as_ref().map(|t| t.def_id()) == tcx.lang_items().deref_trait() {
451 super::build_deref_target_impls(cx, &trait_items, ret);
454 // Return if the trait itself or any types of the generic parameters are doc(hidden).
455 let mut stack: Vec<&Type> = vec![&for_];
457 if let Some(did) = trait_.as_ref().map(|t| t.def_id()) {
458 if tcx.get_attrs(did).lists(sym::doc).has_word(sym::hidden) {
462 if let Some(generics) = trait_.as_ref().and_then(|t| t.generics()) {
463 stack.extend(generics);
466 while let Some(ty) = stack.pop() {
467 if let Some(did) = ty.def_id(&cx.cache) {
468 if tcx.get_attrs(did).lists(sym::doc).has_word(sym::hidden) {
472 if let Some(generics) = ty.generics() {
473 stack.extend(generics);
477 if let Some(did) = trait_.as_ref().map(|t| t.def_id()) {
478 record_extern_trait(cx, did);
481 let (merged_attrs, cfg) = merge_attrs(cx, parent_module.into(), load_attrs(cx, did), attrs);
482 trace!("merged_attrs={:?}", merged_attrs);
485 "build_impl: impl {:?} for {:?}",
486 trait_.as_ref().map(|t| t.def_id()),
487 for_.def_id(&cx.cache)
489 ret.push(clean::Item::from_def_id_and_attrs_and_parts(
492 clean::ImplItem(clean::Impl {
493 span: clean::types::rustc_span(did, cx.tcx),
494 unsafety: hir::Unsafety::Normal,
499 negative_polarity: polarity.clean(cx),
510 cx: &mut DocContext<'_>,
512 visited: &mut FxHashSet<DefId>,
514 let mut items = Vec::new();
516 // If we're re-exporting a re-export it may actually re-export something in
517 // two namespaces, so the target may be listed twice. Make sure we only
518 // visit each node at most once.
519 for &item in cx.tcx.item_children(did).iter() {
520 if item.vis == ty::Visibility::Public {
521 let res = item.res.expect_non_local();
522 if let Some(def_id) = res.mod_def_id() {
523 if did == def_id || !visited.insert(def_id) {
527 if let Res::PrimTy(p) = res {
528 // Primitive types can't be inlined so generate an import instead.
529 let prim_ty = clean::PrimitiveType::from(p);
530 items.push(clean::Item {
532 attrs: box clean::Attributes::default(),
533 def_id: ItemId::Primitive(prim_ty, did.krate),
534 visibility: clean::Public,
535 kind: box clean::ImportItem(clean::Import::new_simple(
537 clean::ImportSource {
540 segments: vec![clean::PathSegment {
541 name: prim_ty.as_sym(),
542 args: clean::GenericArgs::AngleBracketed {
544 bindings: Vec::new(),
554 } else if let Some(i) = try_inline(cx, did, None, res, item.ident.name, None, visited) {
560 let span = clean::Span::new(cx.tcx.def_span(did));
561 clean::Module { items, span }
564 crate fn print_inlined_const(tcx: TyCtxt<'_>, did: DefId) -> String {
565 if let Some(did) = did.as_local() {
566 let hir_id = tcx.hir().local_def_id_to_hir_id(did);
567 rustc_hir_pretty::id_to_string(&tcx.hir(), hir_id)
569 tcx.rendered_const(did)
573 fn build_const(cx: &mut DocContext<'_>, def_id: DefId) -> clean::Constant {
575 type_: cx.tcx.type_of(def_id).clean(cx),
576 kind: clean::ConstantKind::Extern { def_id },
580 fn build_static(cx: &mut DocContext<'_>, did: DefId, mutable: bool) -> clean::Static {
582 type_: cx.tcx.type_of(did).clean(cx),
583 mutability: if mutable { Mutability::Mut } else { Mutability::Not },
589 cx: &mut DocContext<'_>,
592 import_def_id: Option<DefId>,
593 ) -> clean::ItemKind {
594 match CStore::from_tcx(cx.tcx).load_macro_untracked(def_id, cx.sess()) {
595 LoadedMacro::MacroDef(item_def, _) => {
596 if let ast::ItemKind::MacroDef(ref def) = item_def.kind {
597 clean::MacroItem(clean::Macro {
598 source: utils::display_macro_source(
603 cx.tcx.visibility(import_def_id.unwrap_or(def_id)),
610 LoadedMacro::ProcMacro(ext) => clean::ProcMacroItem(clean::ProcMacro {
611 kind: ext.macro_kind(),
612 helpers: ext.helper_attrs,
617 /// A trait's generics clause actually contains all of the predicates for all of
618 /// its associated types as well. We specifically move these clauses to the
619 /// associated types instead when displaying, so when we're generating the
620 /// generics for the trait itself we need to be sure to remove them.
621 /// We also need to remove the implied "recursive" Self: Trait bound.
623 /// The inverse of this filtering logic can be found in the `Clean`
624 /// implementation for `AssociatedType`
625 fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean::Generics {
626 for pred in &mut g.where_predicates {
628 clean::WherePredicate::BoundPredicate {
629 ty: clean::Generic(ref s),
632 } if *s == kw::SelfUpper => {
633 bounds.retain(|bound| match bound {
634 clean::GenericBound::TraitBound(clean::PolyTrait { trait_, .. }, _) => {
635 trait_.def_id() != trait_did
644 g.where_predicates.retain(|pred| match pred {
645 clean::WherePredicate::BoundPredicate {
646 ty: clean::QPath { self_type: box clean::Generic(ref s), trait_, name: _, .. },
649 } => !(bounds.is_empty() || *s == kw::SelfUpper && trait_.def_id() == trait_did),
655 /// Supertrait bounds for a trait are also listed in the generics coming from
656 /// the metadata for a crate, so we want to separate those out and create a new
657 /// list of explicit supertrait bounds to render nicely.
658 fn separate_supertrait_bounds(
659 mut g: clean::Generics,
660 ) -> (clean::Generics, Vec<clean::GenericBound>) {
661 let mut ty_bounds = Vec::new();
662 g.where_predicates.retain(|pred| match *pred {
663 clean::WherePredicate::BoundPredicate { ty: clean::Generic(ref s), ref bounds, .. }
664 if *s == kw::SelfUpper =>
666 ty_bounds.extend(bounds.iter().cloned());
674 crate fn record_extern_trait(cx: &mut DocContext<'_>, did: DefId) {
680 if cx.external_traits.borrow().contains_key(&did) || cx.active_extern_traits.contains(&did)
687 cx.active_extern_traits.insert(did);
690 debug!("record_extern_trait: {:?}", did);
691 let trait_ = build_external_trait(cx, did);
693 let trait_ = clean::TraitWithExtraInfo {
695 is_notable: clean::utils::has_doc_flag(cx.tcx.get_attrs(did), sym::notable_trait),
697 cx.external_traits.borrow_mut().insert(did, trait_);
698 cx.active_extern_traits.remove(&did);