1 //! Support for inlining external documentation into the current AST.
6 use rustc_data_structures::fx::FxHashSet;
8 use rustc_hir::def::{CtorKind, 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;
24 type Attrs<'hir> = rustc_middle::ty::Attributes<'hir>;
26 /// Attempt to inline a definition into this AST.
28 /// This function will fetch the definition specified, and if it is
29 /// from another crate it will attempt to inline the documentation
30 /// from the other crate into this crate.
32 /// This is primarily used for `pub use` statements which are, in general,
33 /// implementation details. Inlining the documentation should help provide a
34 /// better experience when reading the documentation in this use case.
36 /// The returned value is `None` if the definition could not be inlined,
37 /// and `Some` of a vector of items if it was successfully expanded.
39 /// `parent_module` refers to the parent of the *re-export*, not the original item.
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, clean::TypeKind::Trait);
60 ret.extend(build_impls(cx, Some(parent_module), did, attrs));
61 clean::TraitItem(build_external_trait(cx, did))
63 Res::Def(DefKind::Fn, did) => {
64 record_extern_fqn(cx, did, clean::TypeKind::Function);
65 clean::FunctionItem(build_external_function(cx, did))
67 Res::Def(DefKind::Struct, did) => {
68 record_extern_fqn(cx, did, clean::TypeKind::Struct);
69 ret.extend(build_impls(cx, Some(parent_module), did, attrs));
70 clean::StructItem(build_struct(cx, did))
72 Res::Def(DefKind::Union, did) => {
73 record_extern_fqn(cx, did, clean::TypeKind::Union);
74 ret.extend(build_impls(cx, Some(parent_module), did, attrs));
75 clean::UnionItem(build_union(cx, did))
77 Res::Def(DefKind::TyAlias, did) => {
78 record_extern_fqn(cx, did, clean::TypeKind::Typedef);
79 ret.extend(build_impls(cx, Some(parent_module), did, attrs));
80 clean::TypedefItem(build_type_alias(cx, did), false)
82 Res::Def(DefKind::Enum, did) => {
83 record_extern_fqn(cx, did, clean::TypeKind::Enum);
84 ret.extend(build_impls(cx, Some(parent_module), did, attrs));
85 clean::EnumItem(build_enum(cx, did))
87 Res::Def(DefKind::ForeignTy, did) => {
88 record_extern_fqn(cx, did, clean::TypeKind::Foreign);
89 ret.extend(build_impls(cx, Some(parent_module), did, attrs));
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, clean::TypeKind::Module);
99 clean::ModuleItem(build_module(cx, did, visited))
101 Res::Def(DefKind::Static, did) => {
102 record_extern_fqn(cx, did, clean::TypeKind::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, clean::TypeKind::Const);
107 clean::ConstantItem(build_const(cx, did))
109 Res::Def(DefKind::Macro(kind), did) => {
110 let mac = build_macro(cx, did, name);
112 let type_kind = match kind {
113 MacroKind::Bang => TypeKind::Macro,
114 MacroKind::Attr => TypeKind::Attr,
115 MacroKind::Derive => TypeKind::Derive,
117 record_extern_fqn(cx, did, type_kind);
123 let target_attrs = load_attrs(cx, did);
124 let attrs = box merge_attrs(cx, Some(parent_module), target_attrs, attrs_clone);
126 cx.renderinfo.borrow_mut().inlined.insert(did);
127 let what_rustc_thinks = clean::Item::from_def_id_and_parts(did, Some(name), kind, cx);
128 ret.push(clean::Item { attrs, ..what_rustc_thinks });
132 crate fn try_inline_glob(
135 visited: &mut FxHashSet<DefId>,
136 ) -> Option<Vec<clean::Item>> {
140 let did = res.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: &DocContext<'_>, did: DefId, kind: clean::TypeKind) {
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 clean::TypeKind::Macro = kind {
172 // Check to see if it is a macro 2.0 or built-in macro
174 cx.enter_resolver(|r| r.cstore().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.renderinfo.borrow_mut().exact_paths.insert(did, fqn);
190 cx.renderinfo.borrow_mut().external_paths.insert(did, (fqn, kind));
194 crate fn build_external_trait(cx: &DocContext<'_>, did: DefId) -> clean::Trait {
196 cx.tcx.associated_items(did).in_definition_order().map(|item| item.clean(cx)).collect();
198 let predicates = cx.tcx.predicates_of(did);
199 let generics = (cx.tcx.generics_of(did), predicates).clean(cx);
200 let generics = filter_non_trait_generics(did, generics);
201 let (generics, supertrait_bounds) = separate_supertrait_bounds(generics);
202 let is_spotlight = load_attrs(cx, did).clean(cx).has_doc_flag(sym::spotlight);
203 let is_auto = cx.tcx.trait_is_auto(did);
205 unsafety: cx.tcx.trait_def(did).unsafety,
208 bounds: supertrait_bounds,
214 fn build_external_function(cx: &DocContext<'_>, did: DefId) -> clean::Function {
215 let sig = cx.tcx.fn_sig(did);
218 if is_min_const_fn(cx.tcx, did) { hir::Constness::Const } else { hir::Constness::NotConst };
219 let asyncness = cx.tcx.asyncness(did);
220 let predicates = cx.tcx.predicates_of(did);
221 let (generics, decl) = clean::enter_impl_trait(cx, || {
222 ((cx.tcx.generics_of(did), predicates).clean(cx), (did, sig).clean(cx))
224 let (all_types, ret_types) = clean::get_all_types(&generics, &decl, cx);
228 header: hir::FnHeader { unsafety: sig.unsafety(), abi: sig.abi(), constness, asyncness },
234 fn build_enum(cx: &DocContext<'_>, did: DefId) -> clean::Enum {
235 let predicates = cx.tcx.explicit_predicates_of(did);
238 generics: (cx.tcx.generics_of(did), predicates).clean(cx),
239 variants_stripped: false,
240 variants: cx.tcx.adt_def(did).variants.clean(cx),
244 fn build_struct(cx: &DocContext<'_>, did: DefId) -> clean::Struct {
245 let predicates = cx.tcx.explicit_predicates_of(did);
246 let variant = cx.tcx.adt_def(did).non_enum_variant();
249 struct_type: match variant.ctor_kind {
250 CtorKind::Fictive => doctree::Plain,
251 CtorKind::Fn => doctree::Tuple,
252 CtorKind::Const => doctree::Unit,
254 generics: (cx.tcx.generics_of(did), predicates).clean(cx),
255 fields: variant.fields.clean(cx),
256 fields_stripped: false,
260 fn build_union(cx: &DocContext<'_>, did: DefId) -> clean::Union {
261 let predicates = cx.tcx.explicit_predicates_of(did);
262 let variant = cx.tcx.adt_def(did).non_enum_variant();
265 struct_type: doctree::Plain,
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: &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(
286 parent_module: Option<DefId>,
288 attrs: Option<Attrs<'_>>,
289 ) -> Vec<clean::Item> {
291 let mut impls = Vec::new();
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, &mut impls);
301 /// `parent_module` refers to the parent of the re-export, not the original item
304 parent_module: Option<DefId>,
305 old_attrs: Attrs<'_>,
306 new_attrs: Option<Attrs<'_>>,
307 ) -> clean::Attributes {
308 // NOTE: If we have additional attributes (from a re-export),
309 // always insert them first. This ensure that re-export
310 // doc comments show up before the original doc comments
311 // when we render them.
312 if let Some(inner) = new_attrs {
313 if let Some(new_id) = parent_module {
314 let diag = cx.sess().diagnostic();
315 Attributes::from_ast(diag, old_attrs, Some((inner, new_id)))
317 let mut both = inner.to_vec();
318 both.extend_from_slice(old_attrs);
326 /// Builds a specific implementation of a type. The `did` could be a type method or trait method.
329 parent_module: impl Into<Option<DefId>>,
331 attrs: Option<Attrs<'_>>,
332 ret: &mut Vec<clean::Item>,
334 if !cx.renderinfo.borrow_mut().inlined.insert(did) {
339 let associated_trait = tcx.impl_trait_ref(did);
341 // Only inline impl if the implemented trait is
342 // reachable in rustdoc generated documentation
344 if let Some(traitref) = associated_trait {
345 let did = traitref.def_id;
346 if !cx.renderinfo.borrow().access_levels.is_public(did) {
350 if let Some(stab) = tcx.lookup_stability(did) {
351 if stab.level.is_unstable() && stab.feature == sym::rustc_private {
358 let impl_item = match did.as_local() {
360 let hir_id = tcx.hir().local_def_id_to_hir_id(did);
361 match &tcx.hir().expect_item(hir_id).kind {
362 hir::ItemKind::Impl(impl_) => Some(impl_),
363 _ => panic!("`DefID` passed to `build_impl` is not an `impl"),
369 let for_ = match &impl_item {
370 Some(impl_) => impl_.self_ty.clean(cx),
371 None => tcx.type_of(did).clean(cx),
374 // Only inline impl if the implementing type is
375 // reachable in rustdoc generated documentation
377 if let Some(did) = for_.def_id() {
378 if !cx.renderinfo.borrow().access_levels.is_public(did) {
382 if let Some(stab) = tcx.lookup_stability(did) {
383 if stab.level.is_unstable() && stab.feature == sym::rustc_private {
390 let predicates = tcx.explicit_predicates_of(did);
391 let (trait_items, generics) = match impl_item {
396 .map(|item| tcx.hir().impl_item(item.id).clean(cx))
397 .collect::<Vec<_>>(),
398 impl_.generics.clean(cx),
401 tcx.associated_items(did)
402 .in_definition_order()
404 if associated_trait.is_some() || item.vis == ty::Visibility::Public {
410 .collect::<Vec<_>>(),
411 clean::enter_impl_trait(cx, || (tcx.generics_of(did), predicates).clean(cx)),
414 let polarity = tcx.impl_polarity(did);
415 let trait_ = associated_trait.clean(cx).map(|bound| match bound {
416 clean::GenericBound::TraitBound(polyt, _) => polyt.trait_,
417 clean::GenericBound::Outlives(..) => unreachable!(),
419 if trait_.def_id() == tcx.lang_items().deref_trait() {
420 super::build_deref_target_impls(cx, &trait_items, ret);
422 if let Some(trait_did) = trait_.def_id() {
423 record_extern_trait(cx, trait_did);
426 let provided = trait_
428 .map(|did| tcx.provided_trait_methods(did).map(|meth| meth.ident.name).collect())
429 .unwrap_or_default();
431 debug!("build_impl: impl {:?} for {:?}", trait_.def_id(), for_.def_id());
433 let mut item = clean::Item::from_def_id_and_parts(
436 clean::ImplItem(clean::Impl {
437 unsafety: hir::Unsafety::Normal,
439 provided_trait_methods: provided,
443 negative_polarity: polarity.clean(cx),
449 item.attrs = box merge_attrs(cx, parent_module.into(), load_attrs(cx, did), attrs);
450 debug!("merged_attrs={:?}", item.attrs);
454 fn build_module(cx: &DocContext<'_>, did: DefId, visited: &mut FxHashSet<DefId>) -> clean::Module {
455 let mut items = Vec::new();
457 // If we're re-exporting a re-export it may actually re-export something in
458 // two namespaces, so the target may be listed twice. Make sure we only
459 // visit each node at most once.
460 for &item in cx.tcx.item_children(did).iter() {
461 if item.vis == ty::Visibility::Public {
462 if let Some(def_id) = item.res.mod_def_id() {
463 if did == def_id || !visited.insert(def_id) {
467 if let Res::PrimTy(p) = item.res {
468 // Primitive types can't be inlined so generate an import instead.
469 items.push(clean::Item {
471 attrs: box clean::Attributes::default(),
472 source: clean::Span::dummy(),
473 def_id: DefId::local(CRATE_DEF_INDEX),
474 visibility: clean::Public,
475 kind: box clean::ImportItem(clean::Import::new_simple(
477 clean::ImportSource {
481 segments: vec![clean::PathSegment {
482 name: clean::PrimitiveType::from(p).as_sym(),
483 args: clean::GenericArgs::AngleBracketed {
485 bindings: Vec::new(),
494 } else if let Some(i) = try_inline(cx, did, item.res, item.ident.name, None, visited) {
500 clean::Module { items, is_crate: false }
503 crate fn print_inlined_const(cx: &DocContext<'_>, did: DefId) -> String {
504 if let Some(did) = did.as_local() {
505 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(did);
506 rustc_hir_pretty::id_to_string(&cx.tcx.hir(), hir_id)
508 cx.tcx.rendered_const(did)
512 fn build_const(cx: &DocContext<'_>, did: DefId) -> clean::Constant {
514 type_: cx.tcx.type_of(did).clean(cx),
515 expr: print_inlined_const(cx, did),
516 value: clean::utils::print_evaluated_const(cx, did),
517 is_literal: did.as_local().map_or(false, |did| {
518 clean::utils::is_literal_expr(cx, cx.tcx.hir().local_def_id_to_hir_id(did))
523 fn build_static(cx: &DocContext<'_>, did: DefId, mutable: bool) -> clean::Static {
525 type_: cx.tcx.type_of(did).clean(cx),
526 mutability: if mutable { Mutability::Mut } else { Mutability::Not },
527 expr: "\n\n\n".to_string(), // trigger the "[definition]" links
531 fn build_macro(cx: &DocContext<'_>, did: DefId, name: Symbol) -> clean::ItemKind {
532 let imported_from = cx.tcx.original_crate_name(did.krate);
533 match cx.enter_resolver(|r| r.cstore().load_macro_untracked(did, cx.sess())) {
534 LoadedMacro::MacroDef(def, _) => {
535 let matchers: Vec<Span> = if let ast::ItemKind::MacroDef(ref def) = def.kind {
536 let tts: Vec<_> = def.body.inner_tokens().into_trees().collect();
537 tts.chunks(4).map(|arm| arm[0].span()).collect()
542 let source = format!(
543 "macro_rules! {} {{\n{}}}",
547 .map(|span| { format!(" {} => {{ ... }};\n", span.to_src(cx)) })
551 clean::MacroItem(clean::Macro { source, imported_from: Some(imported_from) })
553 LoadedMacro::ProcMacro(ext) => clean::ProcMacroItem(clean::ProcMacro {
554 kind: ext.macro_kind(),
555 helpers: ext.helper_attrs,
560 /// A trait's generics clause actually contains all of the predicates for all of
561 /// its associated types as well. We specifically move these clauses to the
562 /// associated types instead when displaying, so when we're generating the
563 /// generics for the trait itself we need to be sure to remove them.
564 /// We also need to remove the implied "recursive" Self: Trait bound.
566 /// The inverse of this filtering logic can be found in the `Clean`
567 /// implementation for `AssociatedType`
568 fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean::Generics {
569 for pred in &mut g.where_predicates {
571 clean::WherePredicate::BoundPredicate { ty: clean::Generic(ref s), ref mut bounds }
572 if *s == kw::SelfUpper =>
574 bounds.retain(|bound| match *bound {
575 clean::GenericBound::TraitBound(
576 clean::PolyTrait { trait_: clean::ResolvedPath { did, .. }, .. },
578 ) => did != trait_did,
586 g.where_predicates.retain(|pred| match *pred {
587 clean::WherePredicate::BoundPredicate {
590 self_type: box clean::Generic(ref s),
591 trait_: box clean::ResolvedPath { did, .. },
595 } => !(bounds.is_empty() || *s == kw::SelfUpper && did == trait_did),
601 /// Supertrait bounds for a trait are also listed in the generics coming from
602 /// the metadata for a crate, so we want to separate those out and create a new
603 /// list of explicit supertrait bounds to render nicely.
604 fn separate_supertrait_bounds(
605 mut g: clean::Generics,
606 ) -> (clean::Generics, Vec<clean::GenericBound>) {
607 let mut ty_bounds = Vec::new();
608 g.where_predicates.retain(|pred| match *pred {
609 clean::WherePredicate::BoundPredicate { ty: clean::Generic(ref s), ref bounds }
610 if *s == kw::SelfUpper =>
612 ty_bounds.extend(bounds.iter().cloned());
620 crate fn record_extern_trait(cx: &DocContext<'_>, did: DefId) {
626 if cx.external_traits.borrow().contains_key(&did)
627 || cx.active_extern_traits.borrow().contains(&did)
634 cx.active_extern_traits.borrow_mut().insert(did);
637 debug!("record_extern_trait: {:?}", did);
638 let trait_ = build_external_trait(cx, did);
640 cx.external_traits.borrow_mut().insert(did, trait_);
641 cx.active_extern_traits.borrow_mut().remove(&did);