1 //! Support for inlining external documentation into the current AST.
6 use syntax::ext::base::{MacroKind, SyntaxExtension};
10 use rustc::hir::def::{Def, CtorKind};
11 use rustc::hir::def_id::DefId;
12 use rustc_metadata::cstore::LoadedMacro;
14 use rustc::util::nodemap::FxHashSet;
16 use crate::core::{DocContext, DocAccessLevels};
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 visited: &mut FxHashSet<DefId>
44 -> Option<Vec<clean::Item>> {
45 let did = if let Some(did) = def.opt_def_id() {
50 if did.is_local() { return None }
51 let mut ret = Vec::new();
52 let inner = match def {
54 record_extern_fqn(cx, did, clean::TypeKind::Trait);
55 ret.extend(build_impls(cx, did));
56 clean::TraitItem(build_external_trait(cx, did))
59 record_extern_fqn(cx, did, clean::TypeKind::Function);
60 clean::FunctionItem(build_external_function(cx, did))
63 record_extern_fqn(cx, did, clean::TypeKind::Struct);
64 ret.extend(build_impls(cx, did));
65 clean::StructItem(build_struct(cx, did))
68 record_extern_fqn(cx, did, clean::TypeKind::Union);
69 ret.extend(build_impls(cx, did));
70 clean::UnionItem(build_union(cx, did))
72 Def::TyAlias(did) => {
73 record_extern_fqn(cx, did, clean::TypeKind::Typedef);
74 ret.extend(build_impls(cx, did));
75 clean::TypedefItem(build_type_alias(cx, did), false)
78 record_extern_fqn(cx, did, clean::TypeKind::Enum);
79 ret.extend(build_impls(cx, did));
80 clean::EnumItem(build_enum(cx, did))
82 Def::ForeignTy(did) => {
83 record_extern_fqn(cx, did, clean::TypeKind::Foreign);
84 ret.extend(build_impls(cx, did));
85 clean::ForeignTypeItem
87 // Never inline enum variants but leave them shown as re-exports.
88 Def::Variant(..) => return None,
89 // Assume that enum variants and struct types are re-exported next to
90 // their constructors.
91 Def::Ctor(..) | Def::SelfCtor(..) => return Some(Vec::new()),
93 record_extern_fqn(cx, did, clean::TypeKind::Module);
94 clean::ModuleItem(build_module(cx, did, visited))
96 Def::Static(did, mtbl) => {
97 record_extern_fqn(cx, did, clean::TypeKind::Static);
98 clean::StaticItem(build_static(cx, did, mtbl))
101 record_extern_fqn(cx, did, clean::TypeKind::Const);
102 clean::ConstantItem(build_const(cx, did))
104 // FIXME: proc-macros don't propagate attributes or spans across crates, so they look empty
105 Def::Macro(did, MacroKind::Bang) => {
106 let mac = build_macro(cx, did, name);
107 if let clean::MacroItem(..) = mac {
108 record_extern_fqn(cx, did, clean::TypeKind::Macro);
116 cx.renderinfo.borrow_mut().inlined.insert(did);
117 ret.push(clean::Item {
118 source: cx.tcx.def_span(did).clean(cx),
119 name: Some(name.clean(cx)),
120 attrs: load_attrs(cx, did),
122 visibility: Some(clean::Public),
123 stability: cx.tcx.lookup_stability(did).clean(cx),
124 deprecation: cx.tcx.lookup_deprecation(did).clean(cx),
130 pub fn try_inline_glob(cx: &DocContext<'_>, def: Def, visited: &mut FxHashSet<DefId>)
131 -> Option<Vec<clean::Item>>
133 if def == Def::Err { return None }
134 let did = def.def_id();
135 if did.is_local() { return None }
139 let m = build_module(cx, did, visited);
142 // glob imports on things like enums aren't inlined even for local exports, so just bail
147 pub fn load_attrs(cx: &DocContext<'_>, did: DefId) -> clean::Attributes {
148 cx.tcx.get_attrs(did).clean(cx)
151 /// Record an external fully qualified name in the external_paths cache.
153 /// These names are used later on by HTML rendering to generate things like
154 /// source links back to the original item.
155 pub fn record_extern_fqn(cx: &DocContext<'_>, did: DefId, kind: clean::TypeKind) {
156 let mut crate_name = cx.tcx.crate_name(did.krate).to_string();
158 crate_name = cx.crate_name.clone().unwrap_or(crate_name);
161 let relative = cx.tcx.def_path(did).data.into_iter().filter_map(|elem| {
162 // extern blocks have an empty name
163 let s = elem.data.to_string();
170 let fqn = if let clean::TypeKind::Macro = kind {
171 vec![crate_name, relative.last().expect("relative was empty")]
173 once(crate_name).chain(relative).collect()
177 cx.renderinfo.borrow_mut().exact_paths.insert(did, fqn);
179 cx.renderinfo.borrow_mut().external_paths.insert(did, (fqn, kind));
183 pub fn build_external_trait(cx: &DocContext<'_>, did: DefId) -> clean::Trait {
184 let auto_trait = cx.tcx.trait_def(did).has_auto_impl;
185 let trait_items = cx.tcx.associated_items(did).map(|item| item.clean(cx)).collect();
186 let predicates = cx.tcx.predicates_of(did);
187 let generics = (cx.tcx.generics_of(did), &predicates).clean(cx);
188 let generics = filter_non_trait_generics(did, generics);
189 let (generics, supertrait_bounds) = separate_supertrait_bounds(generics);
190 let is_spotlight = load_attrs(cx, did).has_doc_flag("spotlight");
191 let is_auto = cx.tcx.trait_is_auto(did);
194 unsafety: cx.tcx.trait_def(did).unsafety,
197 bounds: supertrait_bounds,
203 fn build_external_function(cx: &DocContext<'_>, did: DefId) -> clean::Function {
204 let sig = cx.tcx.fn_sig(did);
206 let constness = if cx.tcx.is_min_const_fn(did) {
207 hir::Constness::Const
209 hir::Constness::NotConst
212 let predicates = cx.tcx.predicates_of(did);
213 let generics = (cx.tcx.generics_of(did), &predicates).clean(cx);
214 let decl = (did, sig).clean(cx);
215 let (all_types, ret_types) = clean::get_all_types(&generics, &decl, cx);
219 header: hir::FnHeader {
220 unsafety: sig.unsafety(),
223 asyncness: hir::IsAsync::NotAsync,
230 fn build_enum(cx: &DocContext<'_>, did: DefId) -> clean::Enum {
231 let predicates = cx.tcx.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.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.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.predicates_of(did);
272 type_: cx.tcx.type_of(did).clean(cx),
273 generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
277 pub fn build_impls(cx: &DocContext<'_>, did: DefId) -> Vec<clean::Item> {
279 let mut impls = Vec::new();
281 for &did in tcx.inherent_impls(did).iter() {
282 build_impl(cx, did, &mut impls);
288 pub fn build_impl(cx: &DocContext<'_>, did: DefId, ret: &mut Vec<clean::Item>) {
289 if !cx.renderinfo.borrow_mut().inlined.insert(did) {
293 let attrs = load_attrs(cx, did);
295 let associated_trait = tcx.impl_trait_ref(did);
297 // Only inline impl if the implemented trait is
298 // reachable in rustdoc generated documentation
300 if let Some(traitref) = associated_trait {
301 if !cx.renderinfo.borrow().access_levels.is_doc_reachable(traitref.def_id) {
307 let for_ = if let Some(hir_id) = tcx.hir().as_local_hir_id(did) {
308 match tcx.hir().expect_item_by_hir_id(hir_id).node {
309 hir::ItemKind::Impl(.., ref t, _) => {
312 _ => panic!("did given to build_impl was not an impl"),
315 tcx.type_of(did).clean(cx)
318 // Only inline impl if the implementing type is
319 // reachable in rustdoc generated documentation
321 if let Some(did) = for_.def_id() {
322 if !cx.renderinfo.borrow().access_levels.is_doc_reachable(did) {
328 let predicates = tcx.predicates_of(did);
329 let (trait_items, generics) = if let Some(hir_id) = tcx.hir().as_local_hir_id(did) {
330 match tcx.hir().expect_item_by_hir_id(hir_id).node {
331 hir::ItemKind::Impl(.., ref gen, _, _, ref item_ids) => {
334 .map(|ii| tcx.hir().impl_item(ii.id).clean(cx))
335 .collect::<Vec<_>>(),
339 _ => panic!("did given to build_impl was not an impl"),
343 tcx.associated_items(did).filter_map(|item| {
344 if associated_trait.is_some() || item.vis == ty::Visibility::Public {
349 }).collect::<Vec<_>>(),
350 (tcx.generics_of(did), &predicates).clean(cx),
353 let polarity = tcx.impl_polarity(did);
354 let trait_ = associated_trait.clean(cx).map(|bound| {
356 clean::GenericBound::TraitBound(polyt, _) => polyt.trait_,
357 clean::GenericBound::Outlives(..) => unreachable!(),
360 if trait_.def_id() == tcx.lang_items().deref_trait() {
361 super::build_deref_target_impls(cx, &trait_items, ret);
363 if let Some(trait_did) = trait_.def_id() {
364 record_extern_trait(cx, trait_did);
367 let provided = trait_.def_id().map(|did| {
368 tcx.provided_trait_methods(did)
370 .map(|meth| meth.ident.to_string())
372 }).unwrap_or_default();
374 debug!("build_impl: impl {:?} for {:?}", trait_.def_id(), for_.def_id());
376 ret.push(clean::Item {
377 inner: clean::ImplItem(clean::Impl {
378 unsafety: hir::Unsafety::Normal,
380 provided_trait_methods: provided,
384 polarity: Some(polarity.clean(cx)),
388 source: tcx.def_span(did).clean(cx),
391 visibility: Some(clean::Inherited),
392 stability: tcx.lookup_stability(did).clean(cx),
393 deprecation: tcx.lookup_deprecation(did).clean(cx),
401 visited: &mut FxHashSet<DefId>
403 let mut items = Vec::new();
404 fill_in(cx, did, &mut items, visited);
405 return clean::Module {
410 fn fill_in(cx: &DocContext<'_>, did: DefId, items: &mut Vec<clean::Item>,
411 visited: &mut FxHashSet<DefId>) {
412 // If we're re-exporting a re-export it may actually re-export something in
413 // two namespaces, so the target may be listed twice. Make sure we only
414 // visit each node at most once.
415 for &item in cx.tcx.item_children(did).iter() {
416 let def_id = item.def.def_id();
417 if item.vis == ty::Visibility::Public {
418 if did == def_id || !visited.insert(def_id) { continue }
419 if let Some(i) = try_inline(cx, item.def, item.ident.name, visited) {
427 pub fn print_inlined_const(cx: &DocContext<'_>, did: DefId) -> String {
428 if let Some(node_id) = cx.tcx.hir().as_local_hir_id(did) {
429 cx.tcx.hir().hir_to_pretty_string(node_id)
431 cx.tcx.rendered_const(did)
435 fn build_const(cx: &DocContext<'_>, did: DefId) -> clean::Constant {
437 type_: cx.tcx.type_of(did).clean(cx),
438 expr: print_inlined_const(cx, did)
442 fn build_static(cx: &DocContext<'_>, did: DefId, mutable: bool) -> clean::Static {
444 type_: cx.tcx.type_of(did).clean(cx),
445 mutability: if mutable {clean::Mutable} else {clean::Immutable},
446 expr: "\n\n\n".to_string(), // trigger the "[definition]" links
450 fn build_macro(cx: &DocContext<'_>, did: DefId, name: ast::Name) -> clean::ItemEnum {
451 let imported_from = cx.tcx.original_crate_name(did.krate);
452 match cx.cstore.load_macro_untracked(did, cx.sess()) {
453 LoadedMacro::MacroDef(def) => {
454 let matchers: hir::HirVec<Span> = if let ast::ItemKind::MacroDef(ref def) = def.node {
455 let tts: Vec<_> = def.stream().into_trees().collect();
456 tts.chunks(4).map(|arm| arm[0].span()).collect()
461 let source = format!("macro_rules! {} {{\n{}}}",
463 matchers.iter().map(|span| {
464 format!(" {} => {{ ... }};\n", span.to_src(cx))
465 }).collect::<String>());
467 clean::MacroItem(clean::Macro {
469 imported_from: Some(imported_from).clean(cx),
472 LoadedMacro::ProcMacro(ext) => {
473 let helpers = match &*ext {
474 &SyntaxExtension::ProcMacroDerive(_, ref syms, ..) => { syms.clean(cx) }
478 clean::ProcMacroItem(clean::ProcMacro {
487 /// A trait's generics clause actually contains all of the predicates for all of
488 /// its associated types as well. We specifically move these clauses to the
489 /// associated types instead when displaying, so when we're generating the
490 /// generics for the trait itself we need to be sure to remove them.
491 /// We also need to remove the implied "recursive" Self: Trait bound.
493 /// The inverse of this filtering logic can be found in the `Clean`
494 /// implementation for `AssociatedType`
495 fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean::Generics {
496 for pred in &mut g.where_predicates {
498 clean::WherePredicate::BoundPredicate {
499 ty: clean::Generic(ref s),
501 } if *s == "Self" => {
502 bounds.retain(|bound| {
504 clean::GenericBound::TraitBound(clean::PolyTrait {
505 trait_: clean::ResolvedPath { did, .. },
507 }, _) => did != trait_did,
516 g.where_predicates.retain(|pred| {
518 clean::WherePredicate::BoundPredicate {
520 self_type: box clean::Generic(ref s),
521 trait_: box clean::ResolvedPath { did, .. },
524 } => !(*s == "Self" && did == trait_did) && !bounds.is_empty(),
531 /// Supertrait bounds for a trait are also listed in the generics coming from
532 /// the metadata for a crate, so we want to separate those out and create a new
533 /// list of explicit supertrait bounds to render nicely.
534 fn separate_supertrait_bounds(mut g: clean::Generics)
535 -> (clean::Generics, Vec<clean::GenericBound>) {
536 let mut ty_bounds = Vec::new();
537 g.where_predicates.retain(|pred| {
539 clean::WherePredicate::BoundPredicate {
540 ty: clean::Generic(ref s),
542 } if *s == "Self" => {
543 ty_bounds.extend(bounds.iter().cloned());
552 pub fn record_extern_trait(cx: &DocContext<'_>, did: DefId) {
558 let external_traits = cx.external_traits.lock();
559 if external_traits.borrow().contains_key(&did) ||
560 cx.active_extern_traits.borrow().contains(&did)
566 cx.active_extern_traits.borrow_mut().push(did);
568 debug!("record_extern_trait: {:?}", did);
569 let trait_ = build_external_trait(cx, did);
572 let external_traits = cx.external_traits.lock();
573 external_traits.borrow_mut().insert(did, trait_);
575 cx.active_extern_traits.borrow_mut().remove_item(&did);