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.
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 ret.extend(build_impls(cx, Some(parent_module), did, attrs));
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 ret.extend(build_impls(cx, Some(parent_module), did, attrs));
69 clean::StructItem(build_struct(cx, did))
71 Res::Def(DefKind::Union, did) => {
72 record_extern_fqn(cx, did, clean::TypeKind::Union);
73 ret.extend(build_impls(cx, Some(parent_module), did, attrs));
74 clean::UnionItem(build_union(cx, did))
76 Res::Def(DefKind::TyAlias, did) => {
77 record_extern_fqn(cx, did, clean::TypeKind::Typedef);
78 ret.extend(build_impls(cx, Some(parent_module), did, attrs));
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 ret.extend(build_impls(cx, Some(parent_module), did, attrs));
84 clean::EnumItem(build_enum(cx, did))
86 Res::Def(DefKind::ForeignTy, did) => {
87 record_extern_fqn(cx, did, clean::TypeKind::Foreign);
88 ret.extend(build_impls(cx, Some(parent_module), did, attrs));
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(
134 visited: &mut FxHashSet<DefId>,
135 ) -> Option<Vec<clean::Item>> {
139 let did = res.def_id();
145 Res::Def(DefKind::Mod, did) => {
146 let m = build_module(cx, did, visited);
149 // glob imports on things like enums aren't inlined even for local exports, so just bail
154 crate fn load_attrs<'hir>(cx: &DocContext<'hir>, did: DefId) -> Attrs<'hir> {
155 cx.tcx.get_attrs(did)
158 /// Record an external fully qualified name in the external_paths cache.
160 /// These names are used later on by HTML rendering to generate things like
161 /// source links back to the original item.
162 crate fn record_extern_fqn(cx: &DocContext<'_>, did: DefId, kind: clean::TypeKind) {
163 let crate_name = cx.tcx.crate_name(did.krate).to_string();
165 let relative = cx.tcx.def_path(did).data.into_iter().filter_map(|elem| {
166 // extern blocks have an empty name
167 let s = elem.data.to_string();
168 if !s.is_empty() { Some(s) } else { None }
170 let fqn = if let clean::TypeKind::Macro = kind {
171 // Check to see if it is a macro 2.0 or built-in macro
173 cx.enter_resolver(|r| r.cstore().load_macro_untracked(did, cx.sess())),
174 LoadedMacro::MacroDef(def, _)
175 if matches!(&def.kind, ast::ItemKind::MacroDef(ast_def)
176 if !ast_def.macro_rules)
178 once(crate_name).chain(relative).collect()
180 vec![crate_name, relative.last().expect("relative was empty")]
183 once(crate_name).chain(relative).collect()
187 cx.renderinfo.borrow_mut().exact_paths.insert(did, fqn);
189 cx.renderinfo.borrow_mut().external_paths.insert(did, (fqn, kind));
193 crate fn build_external_trait(cx: &DocContext<'_>, did: DefId) -> clean::Trait {
195 cx.tcx.associated_items(did).in_definition_order().map(|item| item.clean(cx)).collect();
197 let predicates = cx.tcx.predicates_of(did);
198 let generics = (cx.tcx.generics_of(did), predicates).clean(cx);
199 let generics = filter_non_trait_generics(did, generics);
200 let (generics, supertrait_bounds) = separate_supertrait_bounds(generics);
201 let is_spotlight = load_attrs(cx, did).clean(cx).has_doc_flag(sym::spotlight);
202 let is_auto = cx.tcx.trait_is_auto(did);
204 unsafety: cx.tcx.trait_def(did).unsafety,
207 bounds: supertrait_bounds,
213 fn build_external_function(cx: &DocContext<'_>, did: DefId) -> clean::Function {
214 let sig = cx.tcx.fn_sig(did);
217 if is_min_const_fn(cx.tcx, did) { hir::Constness::Const } else { hir::Constness::NotConst };
218 let asyncness = cx.tcx.asyncness(did);
219 let predicates = cx.tcx.predicates_of(did);
220 let (generics, decl) = clean::enter_impl_trait(cx, || {
221 ((cx.tcx.generics_of(did), predicates).clean(cx), (did, sig).clean(cx))
223 let (all_types, ret_types) = clean::get_all_types(&generics, &decl, cx);
227 header: hir::FnHeader { unsafety: sig.unsafety(), abi: sig.abi(), constness, asyncness },
233 fn build_enum(cx: &DocContext<'_>, did: DefId) -> clean::Enum {
234 let predicates = cx.tcx.explicit_predicates_of(did);
237 generics: (cx.tcx.generics_of(did), predicates).clean(cx),
238 variants_stripped: false,
239 variants: cx.tcx.adt_def(did).variants.clean(cx),
243 fn build_struct(cx: &DocContext<'_>, did: DefId) -> clean::Struct {
244 let predicates = cx.tcx.explicit_predicates_of(did);
245 let variant = cx.tcx.adt_def(did).non_enum_variant();
248 struct_type: variant.ctor_kind,
249 generics: (cx.tcx.generics_of(did), predicates).clean(cx),
250 fields: variant.fields.clean(cx),
251 fields_stripped: false,
255 fn build_union(cx: &DocContext<'_>, did: DefId) -> clean::Union {
256 let predicates = cx.tcx.explicit_predicates_of(did);
257 let variant = cx.tcx.adt_def(did).non_enum_variant();
260 generics: (cx.tcx.generics_of(did), predicates).clean(cx),
261 fields: variant.fields.clean(cx),
262 fields_stripped: false,
266 fn build_type_alias(cx: &DocContext<'_>, did: DefId) -> clean::Typedef {
267 let predicates = cx.tcx.explicit_predicates_of(did);
268 let type_ = cx.tcx.type_of(did).clean(cx);
272 generics: (cx.tcx.generics_of(did), predicates).clean(cx),
277 /// Builds all inherent implementations of an ADT (struct/union/enum) or Trait item/path/reexport.
278 crate fn build_impls(
280 parent_module: Option<DefId>,
282 attrs: Option<Attrs<'_>>,
283 ) -> Vec<clean::Item> {
285 let mut impls = Vec::new();
287 // for each implementation of an item represented by `did`, build the clean::Item for that impl
288 for &did in tcx.inherent_impls(did).iter() {
289 build_impl(cx, parent_module, did, attrs, &mut impls);
295 /// `parent_module` refers to the parent of the re-export, not the original item
298 parent_module: Option<DefId>,
299 old_attrs: Attrs<'_>,
300 new_attrs: Option<Attrs<'_>>,
301 ) -> clean::Attributes {
302 // NOTE: If we have additional attributes (from a re-export),
303 // always insert them first. This ensure that re-export
304 // doc comments show up before the original doc comments
305 // when we render them.
306 if let Some(inner) = new_attrs {
307 if let Some(new_id) = parent_module {
308 let diag = cx.sess().diagnostic();
309 Attributes::from_ast(diag, old_attrs, Some((inner, new_id)))
311 let mut both = inner.to_vec();
312 both.extend_from_slice(old_attrs);
320 /// Builds a specific implementation of a type. The `did` could be a type method or trait method.
323 parent_module: impl Into<Option<DefId>>,
325 attrs: Option<Attrs<'_>>,
326 ret: &mut Vec<clean::Item>,
328 if !cx.renderinfo.borrow_mut().inlined.insert(did) {
333 let associated_trait = tcx.impl_trait_ref(did);
335 // Only inline impl if the implemented trait is
336 // reachable in rustdoc generated documentation
338 if let Some(traitref) = associated_trait {
339 let did = traitref.def_id;
340 if !cx.renderinfo.borrow().access_levels.is_public(did) {
344 if let Some(stab) = tcx.lookup_stability(did) {
345 if stab.level.is_unstable() && stab.feature == sym::rustc_private {
352 let impl_item = match did.as_local() {
354 let hir_id = tcx.hir().local_def_id_to_hir_id(did);
355 match &tcx.hir().expect_item(hir_id).kind {
356 hir::ItemKind::Impl(impl_) => Some(impl_),
357 _ => panic!("`DefID` passed to `build_impl` is not an `impl"),
363 let for_ = match &impl_item {
364 Some(impl_) => impl_.self_ty.clean(cx),
365 None => tcx.type_of(did).clean(cx),
368 // Only inline impl if the implementing type is
369 // reachable in rustdoc generated documentation
371 if let Some(did) = for_.def_id(&cx.cache) {
372 if !cx.renderinfo.borrow().access_levels.is_public(did) {
376 if let Some(stab) = tcx.lookup_stability(did) {
377 if stab.level.is_unstable() && stab.feature == sym::rustc_private {
384 let predicates = tcx.explicit_predicates_of(did);
385 let (trait_items, generics) = match impl_item {
390 .map(|item| tcx.hir().impl_item(item.id).clean(cx))
391 .collect::<Vec<_>>(),
392 impl_.generics.clean(cx),
395 tcx.associated_items(did)
396 .in_definition_order()
398 if associated_trait.is_some() || item.vis == ty::Visibility::Public {
404 .collect::<Vec<_>>(),
405 clean::enter_impl_trait(cx, || (tcx.generics_of(did), predicates).clean(cx)),
408 let polarity = tcx.impl_polarity(did);
409 let trait_ = associated_trait.clean(cx).map(|bound| match bound {
410 clean::GenericBound::TraitBound(polyt, _) => polyt.trait_,
411 clean::GenericBound::Outlives(..) => unreachable!(),
413 if trait_.def_id(&cx.cache) == tcx.lang_items().deref_trait() {
414 super::build_deref_target_impls(cx, &trait_items, ret);
416 if let Some(trait_did) = trait_.def_id(&cx.cache) {
417 record_extern_trait(cx, trait_did);
420 let provided = trait_
422 .map(|did| tcx.provided_trait_methods(did).map(|meth| meth.ident.name).collect())
423 .unwrap_or_default();
425 debug!("build_impl: impl {:?} for {:?}", trait_.def_id(&cx.cache), for_.def_id(&cx.cache));
427 let mut item = clean::Item::from_def_id_and_parts(
430 clean::ImplItem(clean::Impl {
431 unsafety: hir::Unsafety::Normal,
433 provided_trait_methods: provided,
437 negative_polarity: polarity.clean(cx),
443 item.attrs = box merge_attrs(cx, parent_module.into(), load_attrs(cx, did), attrs);
444 debug!("merged_attrs={:?}", item.attrs);
448 fn build_module(cx: &DocContext<'_>, did: DefId, visited: &mut FxHashSet<DefId>) -> clean::Module {
449 let mut items = Vec::new();
451 // If we're re-exporting a re-export it may actually re-export something in
452 // two namespaces, so the target may be listed twice. Make sure we only
453 // visit each node at most once.
454 for &item in cx.tcx.item_children(did).iter() {
455 if item.vis == ty::Visibility::Public {
456 if let Some(def_id) = item.res.mod_def_id() {
457 if did == def_id || !visited.insert(def_id) {
461 if let Res::PrimTy(p) = item.res {
462 // Primitive types can't be inlined so generate an import instead.
463 items.push(clean::Item {
465 attrs: box clean::Attributes::default(),
466 source: clean::Span::dummy(),
467 def_id: DefId::local(CRATE_DEF_INDEX),
468 visibility: clean::Public,
469 kind: box clean::ImportItem(clean::Import::new_simple(
471 clean::ImportSource {
475 segments: vec![clean::PathSegment {
476 name: clean::PrimitiveType::from(p).as_sym(),
477 args: clean::GenericArgs::AngleBracketed {
479 bindings: Vec::new(),
488 } else if let Some(i) = try_inline(cx, did, item.res, item.ident.name, None, visited) {
494 clean::Module { items, is_crate: false }
497 crate fn print_inlined_const(cx: &DocContext<'_>, did: DefId) -> String {
498 if let Some(did) = did.as_local() {
499 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(did);
500 rustc_hir_pretty::id_to_string(&cx.tcx.hir(), hir_id)
502 cx.tcx.rendered_const(did)
506 fn build_const(cx: &DocContext<'_>, did: DefId) -> clean::Constant {
508 type_: cx.tcx.type_of(did).clean(cx),
509 expr: print_inlined_const(cx, did),
510 value: clean::utils::print_evaluated_const(cx, did),
511 is_literal: did.as_local().map_or(false, |did| {
512 clean::utils::is_literal_expr(cx, cx.tcx.hir().local_def_id_to_hir_id(did))
517 fn build_static(cx: &DocContext<'_>, did: DefId, mutable: bool) -> clean::Static {
519 type_: cx.tcx.type_of(did).clean(cx),
520 mutability: if mutable { Mutability::Mut } else { Mutability::Not },
521 expr: "\n\n\n".to_string(), // trigger the "[definition]" links
525 fn build_macro(cx: &DocContext<'_>, did: DefId, name: Symbol) -> clean::ItemKind {
526 let imported_from = cx.tcx.original_crate_name(did.krate);
527 match cx.enter_resolver(|r| r.cstore().load_macro_untracked(did, cx.sess())) {
528 LoadedMacro::MacroDef(def, _) => {
529 let matchers: Vec<Span> = if let ast::ItemKind::MacroDef(ref def) = def.kind {
530 let tts: Vec<_> = def.body.inner_tokens().into_trees().collect();
531 tts.chunks(4).map(|arm| arm[0].span()).collect()
536 let source = format!(
537 "macro_rules! {} {{\n{}}}",
541 .map(|span| { format!(" {} => {{ ... }};\n", span.to_src(cx)) })
545 clean::MacroItem(clean::Macro { source, imported_from: Some(imported_from) })
547 LoadedMacro::ProcMacro(ext) => clean::ProcMacroItem(clean::ProcMacro {
548 kind: ext.macro_kind(),
549 helpers: ext.helper_attrs,
554 /// A trait's generics clause actually contains all of the predicates for all of
555 /// its associated types as well. We specifically move these clauses to the
556 /// associated types instead when displaying, so when we're generating the
557 /// generics for the trait itself we need to be sure to remove them.
558 /// We also need to remove the implied "recursive" Self: Trait bound.
560 /// The inverse of this filtering logic can be found in the `Clean`
561 /// implementation for `AssociatedType`
562 fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean::Generics {
563 for pred in &mut g.where_predicates {
565 clean::WherePredicate::BoundPredicate { ty: clean::Generic(ref s), ref mut bounds }
566 if *s == kw::SelfUpper =>
568 bounds.retain(|bound| match *bound {
569 clean::GenericBound::TraitBound(
570 clean::PolyTrait { trait_: clean::ResolvedPath { did, .. }, .. },
572 ) => did != trait_did,
580 g.where_predicates.retain(|pred| match *pred {
581 clean::WherePredicate::BoundPredicate {
584 self_type: box clean::Generic(ref s),
585 trait_: box clean::ResolvedPath { did, .. },
589 } => !(bounds.is_empty() || *s == kw::SelfUpper && did == trait_did),
595 /// Supertrait bounds for a trait are also listed in the generics coming from
596 /// the metadata for a crate, so we want to separate those out and create a new
597 /// list of explicit supertrait bounds to render nicely.
598 fn separate_supertrait_bounds(
599 mut g: clean::Generics,
600 ) -> (clean::Generics, Vec<clean::GenericBound>) {
601 let mut ty_bounds = Vec::new();
602 g.where_predicates.retain(|pred| match *pred {
603 clean::WherePredicate::BoundPredicate { ty: clean::Generic(ref s), ref bounds }
604 if *s == kw::SelfUpper =>
606 ty_bounds.extend(bounds.iter().cloned());
614 crate fn record_extern_trait(cx: &DocContext<'_>, did: DefId) {
620 if cx.external_traits.borrow().contains_key(&did)
621 || cx.active_extern_traits.borrow().contains(&did)
628 cx.active_extern_traits.borrow_mut().insert(did);
631 debug!("record_extern_trait: {:?}", did);
632 let trait_ = build_external_trait(cx, did);
634 cx.external_traits.borrow_mut().insert(did, trait_);
635 cx.active_extern_traits.borrow_mut().remove(&did);