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::{sym, Symbol};
18 use crate::clean::{self, 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.
42 attrs: Option<Attrs<'_>>,
43 visited: &mut FxHashSet<DefId>,
44 ) -> Option<Vec<clean::Item>> {
45 let did = res.opt_def_id()?;
49 let mut ret = Vec::new();
51 let attrs_clone = attrs;
53 let inner = match res {
54 Res::Def(DefKind::Trait, did) => {
55 record_extern_fqn(cx, did, clean::TypeKind::Trait);
56 ret.extend(build_impls(cx, did, attrs));
57 clean::TraitItem(build_external_trait(cx, did))
59 Res::Def(DefKind::Fn, did) => {
60 record_extern_fqn(cx, did, clean::TypeKind::Function);
61 clean::FunctionItem(build_external_function(cx, did))
63 Res::Def(DefKind::Struct, did) => {
64 record_extern_fqn(cx, did, clean::TypeKind::Struct);
65 ret.extend(build_impls(cx, did, attrs));
66 clean::StructItem(build_struct(cx, did))
68 Res::Def(DefKind::Union, did) => {
69 record_extern_fqn(cx, did, clean::TypeKind::Union);
70 ret.extend(build_impls(cx, did, attrs));
71 clean::UnionItem(build_union(cx, did))
73 Res::Def(DefKind::TyAlias, did) => {
74 record_extern_fqn(cx, did, clean::TypeKind::Typedef);
75 ret.extend(build_impls(cx, did, attrs));
76 clean::TypedefItem(build_type_alias(cx, did), false)
78 Res::Def(DefKind::Enum, did) => {
79 record_extern_fqn(cx, did, clean::TypeKind::Enum);
80 ret.extend(build_impls(cx, did, attrs));
81 clean::EnumItem(build_enum(cx, did))
83 Res::Def(DefKind::ForeignTy, did) => {
84 record_extern_fqn(cx, did, clean::TypeKind::Foreign);
85 ret.extend(build_impls(cx, did, attrs));
86 clean::ForeignTypeItem
88 // Never inline enum variants but leave them shown as re-exports.
89 Res::Def(DefKind::Variant, _) => return None,
90 // Assume that enum variants and struct types are re-exported next to
91 // their constructors.
92 Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) => return Some(Vec::new()),
93 Res::Def(DefKind::Mod, did) => {
94 record_extern_fqn(cx, did, clean::TypeKind::Module);
95 clean::ModuleItem(build_module(cx, did, visited))
97 Res::Def(DefKind::Static, did) => {
98 record_extern_fqn(cx, did, clean::TypeKind::Static);
99 clean::StaticItem(build_static(cx, did, cx.tcx.is_mutable_static(did)))
101 Res::Def(DefKind::Const, did) => {
102 record_extern_fqn(cx, did, clean::TypeKind::Const);
103 clean::ConstantItem(build_const(cx, did))
105 Res::Def(DefKind::Macro(kind), did) => {
106 let mac = build_macro(cx, did, name);
108 let type_kind = match kind {
109 MacroKind::Bang => TypeKind::Macro,
110 MacroKind::Attr => TypeKind::Attr,
111 MacroKind::Derive => TypeKind::Derive,
113 record_extern_fqn(cx, did, type_kind);
119 let target_attrs = load_attrs(cx, did);
120 let attrs = merge_attrs(cx, target_attrs, attrs_clone);
122 cx.renderinfo.borrow_mut().inlined.insert(did);
123 ret.push(clean::Item {
124 source: cx.tcx.def_span(did).clean(cx),
125 name: Some(name.clean(cx)),
128 visibility: clean::Public,
129 stability: cx.tcx.lookup_stability(did).clean(cx),
130 deprecation: cx.tcx.lookup_deprecation(did).clean(cx),
136 pub fn try_inline_glob(
139 visited: &mut FxHashSet<DefId>,
140 ) -> Option<Vec<clean::Item>> {
144 let did = res.def_id();
150 Res::Def(DefKind::Mod, did) => {
151 let m = build_module(cx, did, visited);
154 // glob imports on things like enums aren't inlined even for local exports, so just bail
159 pub fn load_attrs<'hir>(cx: &DocContext<'hir>, did: DefId) -> Attrs<'hir> {
160 cx.tcx.get_attrs(did)
163 /// Record an external fully qualified name in the external_paths cache.
165 /// These names are used later on by HTML rendering to generate things like
166 /// source links back to the original item.
167 pub fn record_extern_fqn(cx: &DocContext<'_>, did: DefId, kind: clean::TypeKind) {
168 let crate_name = cx.tcx.crate_name(did.krate).to_string();
170 let relative = cx.tcx.def_path(did).data.into_iter().filter_map(|elem| {
171 // extern blocks have an empty name
172 let s = elem.data.to_string();
173 if !s.is_empty() { Some(s) } else { None }
175 let fqn = if let clean::TypeKind::Macro = kind {
176 vec![crate_name, relative.last().expect("relative was empty")]
178 once(crate_name).chain(relative).collect()
182 cx.renderinfo.borrow_mut().exact_paths.insert(did, fqn);
184 cx.renderinfo.borrow_mut().external_paths.insert(did, (fqn, kind));
188 pub fn build_external_trait(cx: &DocContext<'_>, did: DefId) -> clean::Trait {
190 cx.tcx.associated_items(did).in_definition_order().map(|item| item.clean(cx)).collect();
192 let auto_trait = cx.tcx.trait_def(did).has_auto_impl;
193 let predicates = cx.tcx.predicates_of(did);
194 let generics = (cx.tcx.generics_of(did), predicates).clean(cx);
195 let generics = filter_non_trait_generics(did, generics);
196 let (generics, supertrait_bounds) = separate_supertrait_bounds(generics);
197 let is_spotlight = load_attrs(cx, did).clean(cx).has_doc_flag(sym::spotlight);
198 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: &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, || {
218 ((cx.tcx.generics_of(did), predicates).clean(cx), (did, sig).clean(cx))
220 let (all_types, ret_types) = clean::get_all_types(&generics, &decl, cx);
224 header: hir::FnHeader { unsafety: sig.unsafety(), abi: sig.abi(), constness, asyncness },
230 fn build_enum(cx: &DocContext<'_>, did: DefId) -> clean::Enum {
231 let predicates = cx.tcx.explicit_predicates_of(did);
234 generics: (cx.tcx.generics_of(did), predicates).clean(cx),
235 variants_stripped: false,
236 variants: cx.tcx.adt_def(did).variants.clean(cx),
240 fn build_struct(cx: &DocContext<'_>, did: DefId) -> clean::Struct {
241 let predicates = cx.tcx.explicit_predicates_of(did);
242 let variant = cx.tcx.adt_def(did).non_enum_variant();
245 struct_type: match variant.ctor_kind {
246 CtorKind::Fictive => doctree::Plain,
247 CtorKind::Fn => doctree::Tuple,
248 CtorKind::Const => doctree::Unit,
250 generics: (cx.tcx.generics_of(did), predicates).clean(cx),
251 fields: variant.fields.clean(cx),
252 fields_stripped: false,
256 fn build_union(cx: &DocContext<'_>, did: DefId) -> clean::Union {
257 let predicates = cx.tcx.explicit_predicates_of(did);
258 let variant = cx.tcx.adt_def(did).non_enum_variant();
261 struct_type: doctree::Plain,
262 generics: (cx.tcx.generics_of(did), predicates).clean(cx),
263 fields: variant.fields.clean(cx),
264 fields_stripped: false,
268 fn build_type_alias(cx: &DocContext<'_>, did: DefId) -> clean::Typedef {
269 let predicates = cx.tcx.explicit_predicates_of(did);
272 type_: cx.tcx.type_of(did).clean(cx),
273 generics: (cx.tcx.generics_of(did), predicates).clean(cx),
274 item_type: build_type_alias_type(cx, did),
278 fn build_type_alias_type(cx: &DocContext<'_>, did: DefId) -> Option<clean::Type> {
279 let type_ = cx.tcx.type_of(did).clean(cx);
280 type_.def_id().and_then(|did| build_ty(cx, did))
283 pub fn build_ty(cx: &DocContext<'_>, did: DefId) -> Option<clean::Type> {
284 match cx.tcx.def_kind(did) {
285 DefKind::Struct | DefKind::Union | DefKind::Enum | DefKind::Const | DefKind::Static => {
286 Some(cx.tcx.type_of(did).clean(cx))
288 DefKind::TyAlias => build_type_alias_type(cx, did),
293 pub fn build_impls(cx: &DocContext<'_>, did: DefId, attrs: Option<Attrs<'_>>) -> Vec<clean::Item> {
295 let mut impls = Vec::new();
297 for &did in tcx.inherent_impls(did).iter() {
298 build_impl(cx, did, attrs, &mut impls);
307 other_attrs: Option<Attrs<'_>>,
308 ) -> clean::Attributes {
309 let mut merged_attrs: Vec<ast::Attribute> = Vec::with_capacity(attrs.len());
310 // If we have additional attributes (from a re-export),
311 // always insert them first. This ensure that re-export
312 // doc comments show up before the original doc comments
313 // when we render them.
314 if let Some(a) = other_attrs {
315 merged_attrs.extend(a.iter().cloned());
317 merged_attrs.extend(attrs.to_vec());
318 merged_attrs.clean(cx)
324 attrs: Option<Attrs<'_>>,
325 ret: &mut Vec<clean::Item>,
327 if !cx.renderinfo.borrow_mut().inlined.insert(did) {
331 let attrs = merge_attrs(cx, load_attrs(cx, did), attrs);
334 let associated_trait = tcx.impl_trait_ref(did);
336 // Only inline impl if the implemented trait is
337 // reachable in rustdoc generated documentation
339 if let Some(traitref) = associated_trait {
340 if !cx.renderinfo.borrow().access_levels.is_public(traitref.def_id) {
345 // Skip foreign unstable traits from lists of trait implementations and
346 // such. This helps prevent dependencies of the standard library, for
347 // example, from getting documented as "traits `u32` implements" which
348 // isn't really too helpful.
349 if let Some(trait_did) = associated_trait {
350 if let Some(stab) = cx.tcx.lookup_stability(trait_did.def_id) {
351 if stab.level.is_unstable() {
358 let for_ = if let Some(did) = did.as_local() {
359 let hir_id = tcx.hir().local_def_id_to_hir_id(did);
360 match tcx.hir().expect_item(hir_id).kind {
361 hir::ItemKind::Impl { self_ty, .. } => self_ty.clean(cx),
362 _ => panic!("did given to build_impl was not an impl"),
365 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() {
372 if !cx.renderinfo.borrow().access_levels.is_public(did) {
378 let predicates = tcx.explicit_predicates_of(did);
379 let (trait_items, generics) = if let Some(did) = did.as_local() {
380 let hir_id = tcx.hir().local_def_id_to_hir_id(did);
381 match tcx.hir().expect_item(hir_id).kind {
382 hir::ItemKind::Impl { ref generics, ref items, .. } => (
383 items.iter().map(|item| tcx.hir().impl_item(item.id).clean(cx)).collect::<Vec<_>>(),
386 _ => panic!("did given to build_impl was not an impl"),
390 tcx.associated_items(did)
391 .in_definition_order()
393 if associated_trait.is_some() || item.vis == ty::Visibility::Public {
399 .collect::<Vec<_>>(),
400 clean::enter_impl_trait(cx, || (tcx.generics_of(did), predicates).clean(cx)),
403 let polarity = tcx.impl_polarity(did);
404 let trait_ = associated_trait.clean(cx).map(|bound| match bound {
405 clean::GenericBound::TraitBound(polyt, _) => polyt.trait_,
406 clean::GenericBound::Outlives(..) => unreachable!(),
408 if trait_.def_id() == tcx.lang_items().deref_trait() {
409 super::build_deref_target_impls(cx, &trait_items, ret);
411 if let Some(trait_did) = trait_.def_id() {
412 record_extern_trait(cx, trait_did);
415 let provided = trait_
417 .map(|did| tcx.provided_trait_methods(did).map(|meth| meth.ident.to_string()).collect())
418 .unwrap_or_default();
420 debug!("build_impl: impl {:?} for {:?}", trait_.def_id(), for_.def_id());
422 ret.push(clean::Item {
423 inner: clean::ImplItem(clean::Impl {
424 unsafety: hir::Unsafety::Normal,
426 provided_trait_methods: provided,
430 polarity: Some(polarity.clean(cx)),
434 source: tcx.def_span(did).clean(cx),
437 visibility: clean::Inherited,
438 stability: tcx.lookup_stability(did).clean(cx),
439 deprecation: tcx.lookup_deprecation(did).clean(cx),
444 fn build_module(cx: &DocContext<'_>, did: DefId, visited: &mut FxHashSet<DefId>) -> clean::Module {
445 let mut items = Vec::new();
446 fill_in(cx, did, &mut items, visited);
447 return clean::Module { items, is_crate: false };
452 items: &mut Vec<clean::Item>,
453 visited: &mut FxHashSet<DefId>,
455 // If we're re-exporting a re-export it may actually re-export something in
456 // two namespaces, so the target may be listed twice. Make sure we only
457 // visit each node at most once.
458 for &item in cx.tcx.item_children(did).iter() {
459 if item.vis == ty::Visibility::Public {
460 if let Some(def_id) = item.res.mod_def_id() {
461 if did == def_id || !visited.insert(def_id) {
465 if let Res::PrimTy(p) = item.res {
466 // Primitive types can't be inlined so generate an import instead.
467 items.push(clean::Item {
469 attrs: clean::Attributes::default(),
470 source: clean::Span::empty(),
471 def_id: DefId::local(CRATE_DEF_INDEX),
472 visibility: clean::Public,
475 inner: clean::ImportItem(clean::Import::Simple(
476 item.ident.to_string(),
477 clean::ImportSource {
481 segments: vec![clean::PathSegment {
482 name: clean::PrimitiveType::from(p).as_str().to_string(),
483 args: clean::GenericArgs::AngleBracketed {
485 bindings: Vec::new(),
493 } else if let Some(i) = try_inline(cx, item.res, item.ident.name, None, visited) {
501 pub fn print_inlined_const(cx: &DocContext<'_>, did: DefId) -> String {
502 if let Some(did) = did.as_local() {
503 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(did);
504 rustc_hir_pretty::id_to_string(&cx.tcx.hir(), hir_id)
506 cx.tcx.rendered_const(did)
510 fn build_const(cx: &DocContext<'_>, did: DefId) -> clean::Constant {
512 type_: cx.tcx.type_of(did).clean(cx),
513 expr: print_inlined_const(cx, did),
514 value: clean::utils::print_evaluated_const(cx, did),
515 is_literal: did.as_local().map_or(false, |did| {
516 clean::utils::is_literal_expr(cx, cx.tcx.hir().local_def_id_to_hir_id(did))
521 fn build_static(cx: &DocContext<'_>, did: DefId, mutable: bool) -> clean::Static {
523 type_: cx.tcx.type_of(did).clean(cx),
524 mutability: if mutable { Mutability::Mut } else { Mutability::Not },
525 expr: "\n\n\n".to_string(), // trigger the "[definition]" links
529 fn build_macro(cx: &DocContext<'_>, did: DefId, name: Symbol) -> clean::ItemEnum {
530 let imported_from = cx.tcx.original_crate_name(did.krate);
531 match cx.enter_resolver(|r| r.cstore().load_macro_untracked(did, cx.sess())) {
532 LoadedMacro::MacroDef(def, _) => {
533 let matchers: Vec<Span> = if let ast::ItemKind::MacroDef(ref def) = def.kind {
534 let tts: Vec<_> = def.body.inner_tokens().into_trees().collect();
535 tts.chunks(4).map(|arm| arm[0].span()).collect()
540 let source = format!(
541 "macro_rules! {} {{\n{}}}",
545 .map(|span| { format!(" {} => {{ ... }};\n", span.to_src(cx)) })
549 clean::MacroItem(clean::Macro { source, imported_from: Some(imported_from).clean(cx) })
551 LoadedMacro::ProcMacro(ext) => clean::ProcMacroItem(clean::ProcMacro {
552 kind: ext.macro_kind(),
553 helpers: ext.helper_attrs.clean(cx),
558 /// A trait's generics clause actually contains all of the predicates for all of
559 /// its associated types as well. We specifically move these clauses to the
560 /// associated types instead when displaying, so when we're generating the
561 /// generics for the trait itself we need to be sure to remove them.
562 /// We also need to remove the implied "recursive" Self: Trait bound.
564 /// The inverse of this filtering logic can be found in the `Clean`
565 /// implementation for `AssociatedType`
566 fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean::Generics {
567 for pred in &mut g.where_predicates {
569 clean::WherePredicate::BoundPredicate { ty: clean::Generic(ref s), ref mut bounds }
572 bounds.retain(|bound| match *bound {
573 clean::GenericBound::TraitBound(
574 clean::PolyTrait { trait_: clean::ResolvedPath { did, .. }, .. },
576 ) => did != trait_did,
584 g.where_predicates.retain(|pred| match *pred {
585 clean::WherePredicate::BoundPredicate {
588 self_type: box clean::Generic(ref s),
589 trait_: box clean::ResolvedPath { did, .. },
593 } => !(bounds.is_empty() || *s == "Self" && did == trait_did),
599 /// Supertrait bounds for a trait are also listed in the generics coming from
600 /// the metadata for a crate, so we want to separate those out and create a new
601 /// list of explicit supertrait bounds to render nicely.
602 fn separate_supertrait_bounds(
603 mut g: clean::Generics,
604 ) -> (clean::Generics, Vec<clean::GenericBound>) {
605 let mut ty_bounds = Vec::new();
606 g.where_predicates.retain(|pred| match *pred {
607 clean::WherePredicate::BoundPredicate { ty: clean::Generic(ref s), ref bounds }
610 ty_bounds.extend(bounds.iter().cloned());
618 pub fn record_extern_trait(cx: &DocContext<'_>, did: DefId) {
624 if cx.external_traits.borrow().contains_key(&did)
625 || cx.active_extern_traits.borrow().contains(&did)
631 cx.active_extern_traits.borrow_mut().insert(did);
633 debug!("record_extern_trait: {:?}", did);
634 let trait_ = build_external_trait(cx, did);
636 cx.external_traits.borrow_mut().insert(did, trait_);
637 cx.active_extern_traits.borrow_mut().remove(&did);