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::VariantCtor(..) |
93 Def::SelfCtor(..) => return Some(Vec::new()),
95 record_extern_fqn(cx, did, clean::TypeKind::Module);
96 clean::ModuleItem(build_module(cx, did, visited))
98 Def::Static(did, mtbl) => {
99 record_extern_fqn(cx, did, clean::TypeKind::Static);
100 clean::StaticItem(build_static(cx, did, mtbl))
103 record_extern_fqn(cx, did, clean::TypeKind::Const);
104 clean::ConstantItem(build_const(cx, did))
106 // FIXME: proc-macros don't propagate attributes or spans across crates, so they look empty
107 Def::Macro(did, MacroKind::Bang) => {
108 let mac = build_macro(cx, did, name);
109 if let clean::MacroItem(..) = mac {
110 record_extern_fqn(cx, did, clean::TypeKind::Macro);
118 cx.renderinfo.borrow_mut().inlined.insert(did);
119 ret.push(clean::Item {
120 source: cx.tcx.def_span(did).clean(cx),
121 name: Some(name.clean(cx)),
122 attrs: load_attrs(cx, did),
124 visibility: Some(clean::Public),
125 stability: cx.tcx.lookup_stability(did).clean(cx),
126 deprecation: cx.tcx.lookup_deprecation(did).clean(cx),
132 pub fn try_inline_glob(cx: &DocContext<'_>, def: Def, visited: &mut FxHashSet<DefId>)
133 -> Option<Vec<clean::Item>>
135 if def == Def::Err { return None }
136 let did = def.def_id();
137 if did.is_local() { return None }
141 let m = build_module(cx, did, visited);
144 // glob imports on things like enums aren't inlined even for local exports, so just bail
149 pub fn load_attrs(cx: &DocContext<'_>, did: DefId) -> clean::Attributes {
150 cx.tcx.get_attrs(did).clean(cx)
153 /// Record an external fully qualified name in the external_paths cache.
155 /// These names are used later on by HTML rendering to generate things like
156 /// source links back to the original item.
157 pub fn record_extern_fqn(cx: &DocContext<'_>, did: DefId, kind: clean::TypeKind) {
158 let mut crate_name = cx.tcx.crate_name(did.krate).to_string();
160 crate_name = cx.crate_name.clone().unwrap_or(crate_name);
163 let relative = cx.tcx.def_path(did).data.into_iter().filter_map(|elem| {
164 // extern blocks have an empty name
165 let s = elem.data.to_string();
172 let fqn = if let clean::TypeKind::Macro = kind {
173 vec![crate_name, relative.last().expect("relative was empty")]
175 once(crate_name).chain(relative).collect()
179 cx.renderinfo.borrow_mut().exact_paths.insert(did, fqn);
181 cx.renderinfo.borrow_mut().external_paths.insert(did, (fqn, kind));
185 pub fn build_external_trait(cx: &DocContext<'_>, did: DefId) -> clean::Trait {
186 let auto_trait = cx.tcx.trait_def(did).has_auto_impl;
187 let trait_items = cx.tcx.associated_items(did).map(|item| item.clean(cx)).collect();
188 let predicates = cx.tcx.predicates_of(did);
189 let generics = (cx.tcx.generics_of(did), &predicates).clean(cx);
190 let generics = filter_non_trait_generics(did, generics);
191 let (generics, supertrait_bounds) = separate_supertrait_bounds(generics);
192 let is_spotlight = load_attrs(cx, did).has_doc_flag("spotlight");
193 let is_auto = cx.tcx.trait_is_auto(did);
196 unsafety: cx.tcx.trait_def(did).unsafety,
199 bounds: supertrait_bounds,
205 fn build_external_function(cx: &DocContext<'_>, did: DefId) -> clean::Function {
206 let sig = cx.tcx.fn_sig(did);
208 let constness = if cx.tcx.is_min_const_fn(did) {
209 hir::Constness::Const
211 hir::Constness::NotConst
214 let predicates = cx.tcx.predicates_of(did);
216 decl: (did, sig).clean(cx),
217 generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
218 header: hir::FnHeader {
219 unsafety: sig.unsafety(),
222 asyncness: hir::IsAsync::NotAsync,
227 fn build_enum(cx: &DocContext<'_>, did: DefId) -> clean::Enum {
228 let predicates = cx.tcx.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: &DocContext<'_>, did: DefId) -> clean::Struct {
238 let predicates = cx.tcx.predicates_of(did);
239 let variant = cx.tcx.adt_def(did).non_enum_variant();
242 struct_type: match variant.ctor_kind {
243 CtorKind::Fictive => doctree::Plain,
244 CtorKind::Fn => doctree::Tuple,
245 CtorKind::Const => doctree::Unit,
247 generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
248 fields: variant.fields.clean(cx),
249 fields_stripped: false,
253 fn build_union(cx: &DocContext<'_>, did: DefId) -> clean::Union {
254 let predicates = cx.tcx.predicates_of(did);
255 let variant = cx.tcx.adt_def(did).non_enum_variant();
258 struct_type: doctree::Plain,
259 generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
260 fields: variant.fields.clean(cx),
261 fields_stripped: false,
265 fn build_type_alias(cx: &DocContext<'_>, did: DefId) -> clean::Typedef {
266 let predicates = cx.tcx.predicates_of(did);
269 type_: cx.tcx.type_of(did).clean(cx),
270 generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
274 pub fn build_impls(cx: &DocContext<'_>, did: DefId) -> Vec<clean::Item> {
276 let mut impls = Vec::new();
278 for &did in tcx.inherent_impls(did).iter() {
279 build_impl(cx, did, &mut impls);
285 pub fn build_impl(cx: &DocContext<'_>, did: DefId, ret: &mut Vec<clean::Item>) {
286 if !cx.renderinfo.borrow_mut().inlined.insert(did) {
290 let attrs = load_attrs(cx, did);
292 let associated_trait = tcx.impl_trait_ref(did);
294 // Only inline impl if the implemented trait is
295 // reachable in rustdoc generated documentation
297 if let Some(traitref) = associated_trait {
298 if !cx.renderinfo.borrow().access_levels.is_doc_reachable(traitref.def_id) {
304 let for_ = if let Some(hir_id) = tcx.hir().as_local_hir_id(did) {
305 match tcx.hir().expect_item_by_hir_id(hir_id).node {
306 hir::ItemKind::Impl(.., ref t, _) => {
309 _ => panic!("did given to build_impl was not an impl"),
312 tcx.type_of(did).clean(cx)
315 // Only inline impl if the implementing type is
316 // reachable in rustdoc generated documentation
318 if let Some(did) = for_.def_id() {
319 if !cx.renderinfo.borrow().access_levels.is_doc_reachable(did) {
325 let predicates = tcx.predicates_of(did);
326 let (trait_items, generics) = if let Some(hir_id) = tcx.hir().as_local_hir_id(did) {
327 match tcx.hir().expect_item_by_hir_id(hir_id).node {
328 hir::ItemKind::Impl(.., ref gen, _, _, ref item_ids) => {
331 .map(|ii| tcx.hir().impl_item(ii.id).clean(cx))
332 .collect::<Vec<_>>(),
336 _ => panic!("did given to build_impl was not an impl"),
340 tcx.associated_items(did).filter_map(|item| {
341 if associated_trait.is_some() || item.vis == ty::Visibility::Public {
346 }).collect::<Vec<_>>(),
347 (tcx.generics_of(did), &predicates).clean(cx),
350 let polarity = tcx.impl_polarity(did);
351 let trait_ = associated_trait.clean(cx).map(|bound| {
353 clean::GenericBound::TraitBound(polyt, _) => polyt.trait_,
354 clean::GenericBound::Outlives(..) => unreachable!(),
357 if trait_.def_id() == tcx.lang_items().deref_trait() {
358 super::build_deref_target_impls(cx, &trait_items, ret);
360 if let Some(trait_did) = trait_.def_id() {
361 record_extern_trait(cx, trait_did);
364 let provided = trait_.def_id().map(|did| {
365 tcx.provided_trait_methods(did)
367 .map(|meth| meth.ident.to_string())
369 }).unwrap_or_default();
371 debug!("build_impl: impl {:?} for {:?}", trait_.def_id(), for_.def_id());
373 ret.push(clean::Item {
374 inner: clean::ImplItem(clean::Impl {
375 unsafety: hir::Unsafety::Normal,
377 provided_trait_methods: provided,
381 polarity: Some(polarity.clean(cx)),
385 source: tcx.def_span(did).clean(cx),
388 visibility: Some(clean::Inherited),
389 stability: tcx.lookup_stability(did).clean(cx),
390 deprecation: tcx.lookup_deprecation(did).clean(cx),
398 visited: &mut FxHashSet<DefId>
400 let mut items = Vec::new();
401 fill_in(cx, did, &mut items, visited);
402 return clean::Module {
407 fn fill_in(cx: &DocContext<'_>, did: DefId, items: &mut Vec<clean::Item>,
408 visited: &mut FxHashSet<DefId>) {
409 // If we're re-exporting a re-export it may actually re-export something in
410 // two namespaces, so the target may be listed twice. Make sure we only
411 // visit each node at most once.
412 for &item in cx.tcx.item_children(did).iter() {
413 let def_id = item.def.def_id();
414 if item.vis == ty::Visibility::Public {
415 if did == def_id || !visited.insert(def_id) { continue }
416 if let Some(i) = try_inline(cx, item.def, item.ident.name, visited) {
424 pub fn print_inlined_const(cx: &DocContext<'_>, did: DefId) -> String {
425 if let Some(node_id) = cx.tcx.hir().as_local_hir_id(did) {
426 cx.tcx.hir().hir_to_pretty_string(node_id)
428 cx.tcx.rendered_const(did)
432 fn build_const(cx: &DocContext<'_>, did: DefId) -> clean::Constant {
434 type_: cx.tcx.type_of(did).clean(cx),
435 expr: print_inlined_const(cx, did)
439 fn build_static(cx: &DocContext<'_>, did: DefId, mutable: bool) -> clean::Static {
441 type_: cx.tcx.type_of(did).clean(cx),
442 mutability: if mutable {clean::Mutable} else {clean::Immutable},
443 expr: "\n\n\n".to_string(), // trigger the "[definition]" links
447 fn build_macro(cx: &DocContext<'_>, did: DefId, name: ast::Name) -> clean::ItemEnum {
448 let imported_from = cx.tcx.original_crate_name(did.krate);
449 match cx.cstore.load_macro_untracked(did, cx.sess()) {
450 LoadedMacro::MacroDef(def) => {
451 let matchers: hir::HirVec<Span> = if let ast::ItemKind::MacroDef(ref def) = def.node {
452 let tts: Vec<_> = def.stream().into_trees().collect();
453 tts.chunks(4).map(|arm| arm[0].span()).collect()
458 let source = format!("macro_rules! {} {{\n{}}}",
460 matchers.iter().map(|span| {
461 format!(" {} => {{ ... }};\n", span.to_src(cx))
462 }).collect::<String>());
464 clean::MacroItem(clean::Macro {
466 imported_from: Some(imported_from).clean(cx),
469 LoadedMacro::ProcMacro(ext) => {
470 let helpers = match &*ext {
471 &SyntaxExtension::ProcMacroDerive(_, ref syms, ..) => { syms.clean(cx) }
475 clean::ProcMacroItem(clean::ProcMacro {
484 /// A trait's generics clause actually contains all of the predicates for all of
485 /// its associated types as well. We specifically move these clauses to the
486 /// associated types instead when displaying, so when we're generating the
487 /// generics for the trait itself we need to be sure to remove them.
488 /// We also need to remove the implied "recursive" Self: Trait bound.
490 /// The inverse of this filtering logic can be found in the `Clean`
491 /// implementation for `AssociatedType`
492 fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean::Generics {
493 for pred in &mut g.where_predicates {
495 clean::WherePredicate::BoundPredicate {
496 ty: clean::Generic(ref s),
498 } if *s == "Self" => {
499 bounds.retain(|bound| {
501 clean::GenericBound::TraitBound(clean::PolyTrait {
502 trait_: clean::ResolvedPath { did, .. },
504 }, _) => did != trait_did,
513 g.where_predicates.retain(|pred| {
515 clean::WherePredicate::BoundPredicate {
517 self_type: box clean::Generic(ref s),
518 trait_: box clean::ResolvedPath { did, .. },
521 } => !(*s == "Self" && did == trait_did) && !bounds.is_empty(),
528 /// Supertrait bounds for a trait are also listed in the generics coming from
529 /// the metadata for a crate, so we want to separate those out and create a new
530 /// list of explicit supertrait bounds to render nicely.
531 fn separate_supertrait_bounds(mut g: clean::Generics)
532 -> (clean::Generics, Vec<clean::GenericBound>) {
533 let mut ty_bounds = Vec::new();
534 g.where_predicates.retain(|pred| {
536 clean::WherePredicate::BoundPredicate {
537 ty: clean::Generic(ref s),
539 } if *s == "Self" => {
540 ty_bounds.extend(bounds.iter().cloned());
549 pub fn record_extern_trait(cx: &DocContext<'_>, did: DefId) {
555 let external_traits = cx.external_traits.lock();
556 if external_traits.borrow().contains_key(&did) ||
557 cx.active_extern_traits.borrow().contains(&did)
563 cx.active_extern_traits.borrow_mut().push(did);
565 debug!("record_extern_trait: {:?}", did);
566 let trait_ = build_external_trait(cx, did);
569 let external_traits = cx.external_traits.lock();
570 external_traits.borrow_mut().insert(did, trait_);
572 cx.active_extern_traits.borrow_mut().remove_item(&did);