1 //! Support for inlining external documentation into the current AST.
6 use rustc_data_structures::fx::FxHashSet;
8 use rustc_hir::def::{DefKind, Res};
9 use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX};
10 use rustc_hir::Mutability;
11 use rustc_metadata::creader::LoadedMacro;
13 use rustc_mir::const_eval::is_min_const_fn;
14 use rustc_span::hygiene::MacroKind;
15 use rustc_span::symbol::{kw, sym, Symbol};
18 use crate::clean::{self, Attributes, GetDefId, ToSource, TypeKind};
19 use crate::core::DocContext;
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<'_>,
44 attrs: Option<Attrs<'_>>,
45 visited: &mut FxHashSet<DefId>,
46 ) -> Option<Vec<clean::Item>> {
47 let did = res.opt_def_id()?;
51 let mut ret = Vec::new();
53 debug!("attrs={:?}", attrs);
54 let attrs_clone = attrs;
56 let kind = match res {
57 Res::Def(DefKind::Trait, did) => {
58 record_extern_fqn(cx, did, clean::TypeKind::Trait);
59 build_impls(cx, Some(parent_module), did, attrs, &mut ret);
60 clean::TraitItem(build_external_trait(cx, did))
62 Res::Def(DefKind::Fn, did) => {
63 record_extern_fqn(cx, did, clean::TypeKind::Function);
64 clean::FunctionItem(build_external_function(cx, did))
66 Res::Def(DefKind::Struct, did) => {
67 record_extern_fqn(cx, did, clean::TypeKind::Struct);
68 build_impls(cx, Some(parent_module), did, attrs, &mut ret);
69 clean::StructItem(build_struct(cx, did))
71 Res::Def(DefKind::Union, did) => {
72 record_extern_fqn(cx, did, clean::TypeKind::Union);
73 build_impls(cx, Some(parent_module), did, attrs, &mut ret);
74 clean::UnionItem(build_union(cx, did))
76 Res::Def(DefKind::TyAlias, did) => {
77 record_extern_fqn(cx, did, clean::TypeKind::Typedef);
78 build_impls(cx, Some(parent_module), did, attrs, &mut ret);
79 clean::TypedefItem(build_type_alias(cx, did), false)
81 Res::Def(DefKind::Enum, did) => {
82 record_extern_fqn(cx, did, clean::TypeKind::Enum);
83 build_impls(cx, Some(parent_module), did, attrs, &mut ret);
84 clean::EnumItem(build_enum(cx, did))
86 Res::Def(DefKind::ForeignTy, did) => {
87 record_extern_fqn(cx, did, clean::TypeKind::Foreign);
88 build_impls(cx, Some(parent_module), did, attrs, &mut ret);
89 clean::ForeignTypeItem
91 // Never inline enum variants but leave them shown as re-exports.
92 Res::Def(DefKind::Variant, _) => return None,
93 // Assume that enum variants and struct types are re-exported next to
94 // their constructors.
95 Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) => return Some(Vec::new()),
96 Res::Def(DefKind::Mod, did) => {
97 record_extern_fqn(cx, did, clean::TypeKind::Module);
98 clean::ModuleItem(build_module(cx, did, visited))
100 Res::Def(DefKind::Static, did) => {
101 record_extern_fqn(cx, did, clean::TypeKind::Static);
102 clean::StaticItem(build_static(cx, did, cx.tcx.is_mutable_static(did)))
104 Res::Def(DefKind::Const, did) => {
105 record_extern_fqn(cx, did, clean::TypeKind::Const);
106 clean::ConstantItem(build_const(cx, did))
108 Res::Def(DefKind::Macro(kind), did) => {
109 let mac = build_macro(cx, did, name);
111 let type_kind = match kind {
112 MacroKind::Bang => TypeKind::Macro,
113 MacroKind::Attr => TypeKind::Attr,
114 MacroKind::Derive => TypeKind::Derive,
116 record_extern_fqn(cx, did, type_kind);
122 let target_attrs = load_attrs(cx, did);
123 let attrs = box merge_attrs(cx, Some(parent_module), target_attrs, attrs_clone);
125 cx.renderinfo.borrow_mut().inlined.insert(did);
126 let what_rustc_thinks = clean::Item::from_def_id_and_parts(did, Some(name), kind, cx);
127 ret.push(clean::Item { attrs, ..what_rustc_thinks });
131 crate fn try_inline_glob(
132 cx: &mut DocContext<'_>,
134 visited: &mut FxHashSet<DefId>,
135 ) -> Option<Vec<clean::Item>> {
136 let did = res.opt_def_id()?;
142 Res::Def(DefKind::Mod, did) => {
143 let m = build_module(cx, did, visited);
146 // glob imports on things like enums aren't inlined even for local exports, so just bail
151 crate fn load_attrs<'hir>(cx: &DocContext<'hir>, did: DefId) -> Attrs<'hir> {
152 cx.tcx.get_attrs(did)
155 /// Record an external fully qualified name in the external_paths cache.
157 /// These names are used later on by HTML rendering to generate things like
158 /// source links back to the original item.
159 crate fn record_extern_fqn(cx: &DocContext<'_>, did: DefId, kind: clean::TypeKind) {
160 let crate_name = cx.tcx.crate_name(did.krate).to_string();
162 let relative = cx.tcx.def_path(did).data.into_iter().filter_map(|elem| {
163 // extern blocks have an empty name
164 let s = elem.data.to_string();
165 if !s.is_empty() { Some(s) } else { None }
167 let fqn = if let clean::TypeKind::Macro = kind {
168 // Check to see if it is a macro 2.0 or built-in macro
170 cx.enter_resolver(|r| r.cstore().load_macro_untracked(did, cx.sess())),
171 LoadedMacro::MacroDef(def, _)
172 if matches!(&def.kind, ast::ItemKind::MacroDef(ast_def)
173 if !ast_def.macro_rules)
175 once(crate_name).chain(relative).collect()
177 vec![crate_name, relative.last().expect("relative was empty")]
180 once(crate_name).chain(relative).collect()
184 cx.renderinfo.borrow_mut().exact_paths.insert(did, fqn);
186 cx.renderinfo.borrow_mut().external_paths.insert(did, (fqn, kind));
190 crate fn build_external_trait(cx: &mut DocContext<'_>, did: DefId) -> clean::Trait {
192 cx.tcx.associated_items(did).in_definition_order().map(|item| item.clean(cx)).collect();
194 let predicates = cx.tcx.predicates_of(did);
195 let generics = (cx.tcx.generics_of(did), predicates).clean(cx);
196 let generics = filter_non_trait_generics(did, generics);
197 let (generics, supertrait_bounds) = separate_supertrait_bounds(generics);
198 let is_spotlight = load_attrs(cx, did).clean(cx).has_doc_flag(sym::spotlight);
199 let is_auto = cx.tcx.trait_is_auto(did);
201 unsafety: cx.tcx.trait_def(did).unsafety,
204 bounds: supertrait_bounds,
210 fn build_external_function(cx: &mut DocContext<'_>, did: DefId) -> clean::Function {
211 let sig = cx.tcx.fn_sig(did);
214 if is_min_const_fn(cx.tcx, did) { hir::Constness::Const } else { hir::Constness::NotConst };
215 let asyncness = cx.tcx.asyncness(did);
216 let predicates = cx.tcx.predicates_of(did);
217 let (generics, decl) = clean::enter_impl_trait(cx, |cx| {
218 ((cx.tcx.generics_of(did), predicates).clean(cx), (did, sig).clean(cx))
223 header: hir::FnHeader { unsafety: sig.unsafety(), abi: sig.abi(), constness, asyncness },
227 fn build_enum(cx: &mut DocContext<'_>, did: DefId) -> clean::Enum {
228 let predicates = cx.tcx.explicit_predicates_of(did);
231 generics: (cx.tcx.generics_of(did), predicates).clean(cx),
232 variants_stripped: false,
233 variants: cx.tcx.adt_def(did).variants.clean(cx),
237 fn build_struct(cx: &mut DocContext<'_>, did: DefId) -> clean::Struct {
238 let predicates = cx.tcx.explicit_predicates_of(did);
239 let variant = cx.tcx.adt_def(did).non_enum_variant();
242 struct_type: variant.ctor_kind,
243 generics: (cx.tcx.generics_of(did), predicates).clean(cx),
244 fields: variant.fields.clean(cx),
245 fields_stripped: false,
249 fn build_union(cx: &mut DocContext<'_>, did: DefId) -> clean::Union {
250 let predicates = cx.tcx.explicit_predicates_of(did);
251 let variant = cx.tcx.adt_def(did).non_enum_variant();
254 generics: (cx.tcx.generics_of(did), predicates).clean(cx),
255 fields: variant.fields.clean(cx),
256 fields_stripped: false,
260 fn build_type_alias(cx: &mut DocContext<'_>, did: DefId) -> clean::Typedef {
261 let predicates = cx.tcx.explicit_predicates_of(did);
262 let type_ = cx.tcx.type_of(did).clean(cx);
266 generics: (cx.tcx.generics_of(did), predicates).clean(cx),
271 /// Builds all inherent implementations of an ADT (struct/union/enum) or Trait item/path/reexport.
272 crate fn build_impls(
273 cx: &mut DocContext<'_>,
274 parent_module: Option<DefId>,
276 attrs: Option<Attrs<'_>>,
277 ret: &mut Vec<clean::Item>,
281 // for each implementation of an item represented by `did`, build the clean::Item for that impl
282 for &did in tcx.inherent_impls(did).iter() {
283 build_impl(cx, parent_module, did, attrs, ret);
287 /// `parent_module` refers to the parent of the re-export, not the original item
289 cx: &mut DocContext<'_>,
290 parent_module: Option<DefId>,
291 old_attrs: Attrs<'_>,
292 new_attrs: Option<Attrs<'_>>,
293 ) -> clean::Attributes {
294 // NOTE: If we have additional attributes (from a re-export),
295 // always insert them first. This ensure that re-export
296 // doc comments show up before the original doc comments
297 // when we render them.
298 if let Some(inner) = new_attrs {
299 if let Some(new_id) = parent_module {
300 let diag = cx.sess().diagnostic();
301 Attributes::from_ast(diag, old_attrs, Some((inner, new_id)))
303 let mut both = inner.to_vec();
304 both.extend_from_slice(old_attrs);
312 /// Builds a specific implementation of a type. The `did` could be a type method or trait method.
314 cx: &mut DocContext<'_>,
315 parent_module: impl Into<Option<DefId>>,
317 attrs: Option<Attrs<'_>>,
318 ret: &mut Vec<clean::Item>,
320 if !cx.renderinfo.borrow_mut().inlined.insert(did) {
325 let associated_trait = tcx.impl_trait_ref(did);
327 // Only inline impl if the implemented trait is
328 // reachable in rustdoc generated documentation
330 if let Some(traitref) = associated_trait {
331 let did = traitref.def_id;
332 if !cx.renderinfo.borrow().access_levels.is_public(did) {
336 if let Some(stab) = tcx.lookup_stability(did) {
337 if stab.level.is_unstable() && stab.feature == sym::rustc_private {
344 let impl_item = match did.as_local() {
346 let hir_id = tcx.hir().local_def_id_to_hir_id(did);
347 match &tcx.hir().expect_item(hir_id).kind {
348 hir::ItemKind::Impl(impl_) => Some(impl_),
349 _ => panic!("`DefID` passed to `build_impl` is not an `impl"),
355 let for_ = match &impl_item {
356 Some(impl_) => impl_.self_ty.clean(cx),
357 None => tcx.type_of(did).clean(cx),
360 // Only inline impl if the implementing type is
361 // reachable in rustdoc generated documentation
363 if let Some(did) = for_.def_id() {
364 if !cx.renderinfo.borrow().access_levels.is_public(did) {
368 if let Some(stab) = tcx.lookup_stability(did) {
369 if stab.level.is_unstable() && stab.feature == sym::rustc_private {
376 let predicates = tcx.explicit_predicates_of(did);
377 let (trait_items, generics) = match impl_item {
382 .map(|item| tcx.hir().impl_item(item.id).clean(cx))
383 .collect::<Vec<_>>(),
384 impl_.generics.clean(cx),
387 tcx.associated_items(did)
388 .in_definition_order()
390 if associated_trait.is_some() || item.vis == ty::Visibility::Public {
396 .collect::<Vec<_>>(),
397 clean::enter_impl_trait(cx, |cx| (tcx.generics_of(did), predicates).clean(cx)),
400 let polarity = tcx.impl_polarity(did);
401 let trait_ = associated_trait.clean(cx).map(|bound| match bound {
402 clean::GenericBound::TraitBound(polyt, _) => polyt.trait_,
403 clean::GenericBound::Outlives(..) => unreachable!(),
405 if trait_.def_id() == tcx.lang_items().deref_trait() {
406 super::build_deref_target_impls(cx, &trait_items, ret);
408 if let Some(trait_did) = trait_.def_id() {
409 record_extern_trait(cx, trait_did);
412 let provided = trait_
414 .map(|did| tcx.provided_trait_methods(did).map(|meth| meth.ident.name).collect())
415 .unwrap_or_default();
417 debug!("build_impl: impl {:?} for {:?}", trait_.def_id(), for_.def_id());
419 let mut item = clean::Item::from_def_id_and_parts(
422 clean::ImplItem(clean::Impl {
423 unsafety: hir::Unsafety::Normal,
425 provided_trait_methods: provided,
429 negative_polarity: polarity.clean(cx),
435 item.attrs = box merge_attrs(cx, parent_module.into(), load_attrs(cx, did), attrs);
436 debug!("merged_attrs={:?}", item.attrs);
441 cx: &mut DocContext<'_>,
443 visited: &mut FxHashSet<DefId>,
445 let mut items = Vec::new();
447 // If we're re-exporting a re-export it may actually re-export something in
448 // two namespaces, so the target may be listed twice. Make sure we only
449 // visit each node at most once.
450 for &item in cx.tcx.item_children(did).iter() {
451 if item.vis == ty::Visibility::Public {
452 if let Some(def_id) = item.res.mod_def_id() {
453 if did == def_id || !visited.insert(def_id) {
457 if let Res::PrimTy(p) = item.res {
458 // Primitive types can't be inlined so generate an import instead.
459 items.push(clean::Item {
461 attrs: box clean::Attributes::default(),
462 source: clean::Span::dummy(),
463 def_id: DefId::local(CRATE_DEF_INDEX),
464 visibility: clean::Public,
465 kind: box clean::ImportItem(clean::Import::new_simple(
467 clean::ImportSource {
471 segments: vec![clean::PathSegment {
472 name: clean::PrimitiveType::from(p).as_sym(),
473 args: clean::GenericArgs::AngleBracketed {
475 bindings: Vec::new(),
484 } else if let Some(i) = try_inline(cx, did, item.res, item.ident.name, None, visited) {
490 clean::Module { items, is_crate: false }
493 crate fn print_inlined_const(cx: &DocContext<'_>, did: DefId) -> String {
494 if let Some(did) = did.as_local() {
495 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(did);
496 rustc_hir_pretty::id_to_string(&cx.tcx.hir(), hir_id)
498 cx.tcx.rendered_const(did)
502 fn build_const(cx: &mut DocContext<'_>, did: DefId) -> clean::Constant {
504 type_: cx.tcx.type_of(did).clean(cx),
505 expr: print_inlined_const(cx, did),
506 value: clean::utils::print_evaluated_const(cx, did),
507 is_literal: did.as_local().map_or(false, |did| {
508 clean::utils::is_literal_expr(cx, cx.tcx.hir().local_def_id_to_hir_id(did))
513 fn build_static(cx: &mut DocContext<'_>, did: DefId, mutable: bool) -> clean::Static {
515 type_: cx.tcx.type_of(did).clean(cx),
516 mutability: if mutable { Mutability::Mut } else { Mutability::Not },
521 fn build_macro(cx: &mut DocContext<'_>, did: DefId, name: Symbol) -> clean::ItemKind {
522 let imported_from = cx.tcx.original_crate_name(did.krate);
523 match cx.enter_resolver(|r| r.cstore().load_macro_untracked(did, cx.sess())) {
524 LoadedMacro::MacroDef(def, _) => {
525 let matchers: Vec<Span> = if let ast::ItemKind::MacroDef(ref def) = def.kind {
526 let tts: Vec<_> = def.body.inner_tokens().into_trees().collect();
527 tts.chunks(4).map(|arm| arm[0].span()).collect()
532 let source = format!(
533 "macro_rules! {} {{\n{}}}",
537 .map(|span| { format!(" {} => {{ ... }};\n", span.to_src(cx)) })
541 clean::MacroItem(clean::Macro { source, imported_from: Some(imported_from) })
543 LoadedMacro::ProcMacro(ext) => clean::ProcMacroItem(clean::ProcMacro {
544 kind: ext.macro_kind(),
545 helpers: ext.helper_attrs,
550 /// A trait's generics clause actually contains all of the predicates for all of
551 /// its associated types as well. We specifically move these clauses to the
552 /// associated types instead when displaying, so when we're generating the
553 /// generics for the trait itself we need to be sure to remove them.
554 /// We also need to remove the implied "recursive" Self: Trait bound.
556 /// The inverse of this filtering logic can be found in the `Clean`
557 /// implementation for `AssociatedType`
558 fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean::Generics {
559 for pred in &mut g.where_predicates {
561 clean::WherePredicate::BoundPredicate { ty: clean::Generic(ref s), ref mut bounds }
562 if *s == kw::SelfUpper =>
564 bounds.retain(|bound| match *bound {
565 clean::GenericBound::TraitBound(
566 clean::PolyTrait { trait_: clean::ResolvedPath { did, .. }, .. },
568 ) => did != trait_did,
576 g.where_predicates.retain(|pred| match *pred {
577 clean::WherePredicate::BoundPredicate {
580 self_type: box clean::Generic(ref s),
581 trait_: box clean::ResolvedPath { did, .. },
585 } => !(bounds.is_empty() || *s == kw::SelfUpper && did == trait_did),
591 /// Supertrait bounds for a trait are also listed in the generics coming from
592 /// the metadata for a crate, so we want to separate those out and create a new
593 /// list of explicit supertrait bounds to render nicely.
594 fn separate_supertrait_bounds(
595 mut g: clean::Generics,
596 ) -> (clean::Generics, Vec<clean::GenericBound>) {
597 let mut ty_bounds = Vec::new();
598 g.where_predicates.retain(|pred| match *pred {
599 clean::WherePredicate::BoundPredicate { ty: clean::Generic(ref s), ref bounds }
600 if *s == kw::SelfUpper =>
602 ty_bounds.extend(bounds.iter().cloned());
610 crate fn record_extern_trait(cx: &mut DocContext<'_>, did: DefId) {
616 if cx.external_traits.borrow().contains_key(&did)
617 || cx.active_extern_traits.borrow().contains(&did)
624 cx.active_extern_traits.borrow_mut().insert(did);
627 debug!("record_extern_trait: {:?}", did);
628 let trait_ = build_external_trait(cx, did);
630 cx.external_traits.borrow_mut().insert(did, trait_);
631 cx.active_extern_traits.borrow_mut().remove(&did);