1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Support for inlining external documentation into the current AST.
16 use syntax::ext::base::MacroKind;
20 use rustc::hir::def::{Def, CtorKind};
21 use rustc::hir::def_id::DefId;
22 use rustc_metadata::cstore::LoadedMacro;
24 use rustc::util::nodemap::FxHashSet;
26 use core::{DocContext, DocAccessLevels};
32 get_auto_traits_with_def_id,
33 get_blanket_impls_with_def_id,
38 /// Attempt to inline a definition into this AST.
40 /// This function will fetch the definition specified, and if it is
41 /// from another crate it will attempt to inline the documentation
42 /// from the other crate into this crate.
44 /// This is primarily used for `pub use` statements which are, in general,
45 /// implementation details. Inlining the documentation should help provide a
46 /// better experience when reading the documentation in this use case.
48 /// The returned value is `None` if the definition could not be inlined,
49 /// and `Some` of a vector of items if it was successfully expanded.
50 pub fn try_inline(cx: &DocContext, def: Def, name: ast::Name, visited: &mut FxHashSet<DefId>)
51 -> Option<Vec<clean::Item>> {
52 if def == Def::Err { return None }
53 let did = def.def_id();
54 if did.is_local() { return None }
55 let mut ret = Vec::new();
56 let inner = match def {
58 record_extern_fqn(cx, did, clean::TypeKind::Trait);
59 ret.extend(build_impls(cx, did, false));
60 clean::TraitItem(build_external_trait(cx, did))
63 record_extern_fqn(cx, did, clean::TypeKind::Function);
64 clean::FunctionItem(build_external_function(cx, did))
67 record_extern_fqn(cx, did, clean::TypeKind::Struct);
68 ret.extend(build_impls(cx, did, true));
69 clean::StructItem(build_struct(cx, did))
72 record_extern_fqn(cx, did, clean::TypeKind::Union);
73 ret.extend(build_impls(cx, did, true));
74 clean::UnionItem(build_union(cx, did))
76 Def::TyAlias(did) => {
77 record_extern_fqn(cx, did, clean::TypeKind::Typedef);
78 ret.extend(build_impls(cx, did, false));
79 clean::TypedefItem(build_type_alias(cx, did), false)
82 record_extern_fqn(cx, did, clean::TypeKind::Enum);
83 ret.extend(build_impls(cx, did, true));
84 clean::EnumItem(build_enum(cx, did))
86 Def::ForeignTy(did) => {
87 record_extern_fqn(cx, did, clean::TypeKind::Foreign);
88 ret.extend(build_impls(cx, did, false));
89 clean::ForeignTypeItem
91 // Never inline enum variants but leave them shown as re-exports.
92 Def::Variant(..) => return None,
93 // Assume that enum variants and struct types are re-exported next to
94 // their constructors.
95 Def::VariantCtor(..) |
96 Def::StructCtor(..) => return Some(Vec::new()),
98 record_extern_fqn(cx, did, clean::TypeKind::Module);
99 clean::ModuleItem(build_module(cx, did, visited))
101 Def::Static(did, mtbl) => {
102 record_extern_fqn(cx, did, clean::TypeKind::Static);
103 clean::StaticItem(build_static(cx, did, mtbl))
106 record_extern_fqn(cx, did, clean::TypeKind::Const);
107 clean::ConstantItem(build_const(cx, did))
109 // FIXME(misdreavus): if attributes/derives come down here we should probably document them
111 Def::Macro(did, MacroKind::Bang) => {
112 record_extern_fqn(cx, did, clean::TypeKind::Macro);
113 if let Some(mac) = build_macro(cx, did, name) {
114 clean::MacroItem(mac)
121 cx.renderinfo.borrow_mut().inlined.insert(did);
122 ret.push(clean::Item {
123 source: cx.tcx.def_span(did).clean(cx),
124 name: Some(name.clean(cx)),
125 attrs: load_attrs(cx, did),
127 visibility: Some(clean::Public),
128 stability: cx.tcx.lookup_stability(did).clean(cx),
129 deprecation: cx.tcx.lookup_deprecation(did).clean(cx),
135 pub fn try_inline_glob(cx: &DocContext, def: Def, visited: &mut FxHashSet<DefId>)
136 -> Option<Vec<clean::Item>>
138 if def == Def::Err { return None }
139 let did = def.def_id();
140 if did.is_local() { return None }
144 let m = build_module(cx, did, visited);
147 // glob imports on things like enums aren't inlined even for local exports, so just bail
152 pub fn load_attrs(cx: &DocContext, did: DefId) -> clean::Attributes {
153 cx.tcx.get_attrs(did).clean(cx)
156 /// Record an external fully qualified name in the external_paths cache.
158 /// These names are used later on by HTML rendering to generate things like
159 /// source links back to the original item.
160 pub fn record_extern_fqn(cx: &DocContext, did: DefId, kind: clean::TypeKind) {
162 debug!("record_extern_fqn(did={:?}, kind+{:?}): def_id is local, aborting", did, kind);
166 let crate_name = cx.tcx.crate_name(did.krate).to_string();
167 let relative = cx.tcx.def_path(did).data.into_iter().filter_map(|elem| {
168 // extern blocks have an empty name
169 let s = elem.data.to_string();
176 let fqn = if let clean::TypeKind::Macro = kind {
177 vec![crate_name, relative.last().expect("relative was empty")]
179 once(crate_name).chain(relative).collect()
181 cx.renderinfo.borrow_mut().external_paths.insert(did, (fqn, kind));
184 pub fn build_external_trait(cx: &DocContext, did: DefId) -> clean::Trait {
185 let auto_trait = cx.tcx.trait_def(did).has_auto_impl;
186 let trait_items = cx.tcx.associated_items(did).map(|item| item.clean(cx)).collect();
187 let predicates = cx.tcx.predicates_of(did);
188 let generics = (cx.tcx.generics_of(did), &predicates).clean(cx);
189 let generics = filter_non_trait_generics(did, generics);
190 let (generics, supertrait_bounds) = separate_supertrait_bounds(generics);
191 let is_spotlight = load_attrs(cx, did).has_doc_flag("spotlight");
192 let is_auto = cx.tcx.trait_is_auto(did);
195 unsafety: cx.tcx.trait_def(did).unsafety,
198 bounds: supertrait_bounds,
204 fn build_external_function(cx: &DocContext, did: DefId) -> clean::Function {
205 let sig = cx.tcx.fn_sig(did);
207 let constness = if cx.tcx.is_const_fn(did) {
208 hir::Constness::Const
210 hir::Constness::NotConst
213 let predicates = cx.tcx.predicates_of(did);
215 decl: (did, sig).clean(cx),
216 generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
217 header: hir::FnHeader {
218 unsafety: sig.unsafety(),
221 asyncness: hir::IsAsync::NotAsync,
226 fn build_enum(cx: &DocContext, did: DefId) -> clean::Enum {
227 let predicates = cx.tcx.predicates_of(did);
230 generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
231 variants_stripped: false,
232 variants: cx.tcx.adt_def(did).variants.clean(cx),
236 fn build_struct(cx: &DocContext, did: DefId) -> clean::Struct {
237 let predicates = cx.tcx.predicates_of(did);
238 let variant = cx.tcx.adt_def(did).non_enum_variant();
241 struct_type: match variant.ctor_kind {
242 CtorKind::Fictive => doctree::Plain,
243 CtorKind::Fn => doctree::Tuple,
244 CtorKind::Const => doctree::Unit,
246 generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
247 fields: variant.fields.clean(cx),
248 fields_stripped: false,
252 fn build_union(cx: &DocContext, did: DefId) -> clean::Union {
253 let predicates = cx.tcx.predicates_of(did);
254 let variant = cx.tcx.adt_def(did).non_enum_variant();
257 struct_type: doctree::Plain,
258 generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
259 fields: variant.fields.clean(cx),
260 fields_stripped: false,
264 fn build_type_alias(cx: &DocContext, did: DefId) -> clean::Typedef {
265 let predicates = cx.tcx.predicates_of(did);
268 type_: cx.tcx.type_of(did).clean(cx),
269 generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
273 pub fn build_impls(cx: &DocContext, did: DefId, auto_traits: bool) -> Vec<clean::Item> {
275 let mut impls = Vec::new();
277 for &did in tcx.inherent_impls(did).iter() {
278 build_impl(cx, did, &mut impls);
282 let auto_impls = get_auto_traits_with_def_id(cx, did);
284 let mut renderinfo = cx.renderinfo.borrow_mut();
285 let new_impls: Vec<clean::Item> = auto_impls.into_iter()
286 .filter(|i| renderinfo.inlined.insert(i.def_id)).collect();
288 impls.extend(new_impls);
290 impls.extend(get_blanket_impls_with_def_id(cx, did));
293 // If this is the first time we've inlined something from another crate, then
294 // we inline *all* impls from all the crates into this crate. Note that there's
295 // currently no way for us to filter this based on type, and we likely need
296 // many impls for a variety of reasons.
298 // Primarily, the impls will be used to populate the documentation for this
299 // type being inlined, but impls can also be used when generating
300 // documentation for primitives (no way to find those specifically).
301 if cx.populated_all_crate_impls.get() {
305 cx.populated_all_crate_impls.set(true);
307 for &cnum in tcx.crates().iter() {
308 for did in tcx.all_trait_implementations(cnum).iter() {
309 build_impl(cx, *did, &mut impls);
313 // Also try to inline primitive impls from other crates.
314 let lang_items = tcx.lang_items();
315 let primitive_impls = [
316 lang_items.isize_impl(),
317 lang_items.i8_impl(),
318 lang_items.i16_impl(),
319 lang_items.i32_impl(),
320 lang_items.i64_impl(),
321 lang_items.i128_impl(),
322 lang_items.usize_impl(),
323 lang_items.u8_impl(),
324 lang_items.u16_impl(),
325 lang_items.u32_impl(),
326 lang_items.u64_impl(),
327 lang_items.u128_impl(),
328 lang_items.f32_impl(),
329 lang_items.f64_impl(),
330 lang_items.f32_runtime_impl(),
331 lang_items.f64_runtime_impl(),
332 lang_items.char_impl(),
333 lang_items.str_impl(),
334 lang_items.slice_impl(),
335 lang_items.slice_u8_impl(),
336 lang_items.str_alloc_impl(),
337 lang_items.slice_alloc_impl(),
338 lang_items.slice_u8_alloc_impl(),
339 lang_items.const_ptr_impl(),
340 lang_items.mut_ptr_impl(),
343 for def_id in primitive_impls.iter().filter_map(|&def_id| def_id) {
344 if !def_id.is_local() {
345 build_impl(cx, def_id, &mut impls);
347 let auto_impls = get_auto_traits_with_def_id(cx, def_id);
348 let blanket_impls = get_blanket_impls_with_def_id(cx, def_id);
349 let mut renderinfo = cx.renderinfo.borrow_mut();
351 let new_impls: Vec<clean::Item> = auto_impls.into_iter()
352 .chain(blanket_impls.into_iter())
353 .filter(|i| renderinfo.inlined.insert(i.def_id))
356 impls.extend(new_impls);
363 pub fn build_impl(cx: &DocContext, did: DefId, ret: &mut Vec<clean::Item>) {
364 if !cx.renderinfo.borrow_mut().inlined.insert(did) {
368 let attrs = load_attrs(cx, did);
370 let associated_trait = tcx.impl_trait_ref(did);
372 // Only inline impl if the implemented trait is
373 // reachable in rustdoc generated documentation
374 if let Some(traitref) = associated_trait {
375 if !cx.access_levels.borrow().is_doc_reachable(traitref.def_id) {
380 let for_ = tcx.type_of(did).clean(cx);
382 // Only inline impl if the implementing type is
383 // reachable in rustdoc generated documentation
384 if let Some(did) = for_.def_id() {
385 if !cx.access_levels.borrow().is_doc_reachable(did) {
390 let predicates = tcx.predicates_of(did);
391 let trait_items = tcx.associated_items(did).filter_map(|item| {
392 if associated_trait.is_some() || item.vis == ty::Visibility::Public {
397 }).collect::<Vec<_>>();
398 let polarity = tcx.impl_polarity(did);
399 let trait_ = associated_trait.clean(cx).map(|bound| {
401 clean::GenericBound::TraitBound(polyt, _) => polyt.trait_,
402 clean::GenericBound::Outlives(..) => unreachable!(),
405 if trait_.def_id() == tcx.lang_items().deref_trait() {
406 super::build_deref_target_impls(cx, &trait_items, ret);
408 if let Some(trait_did) = trait_.def_id() {
409 record_extern_trait(cx, trait_did);
412 let provided = trait_.def_id().map(|did| {
413 tcx.provided_trait_methods(did)
415 .map(|meth| meth.ident.to_string())
417 }).unwrap_or(FxHashSet());
419 ret.push(clean::Item {
420 inner: clean::ImplItem(clean::Impl {
421 unsafety: hir::Unsafety::Normal,
422 generics: (tcx.generics_of(did), &predicates).clean(cx),
423 provided_trait_methods: provided,
427 polarity: Some(polarity.clean(cx)),
431 source: tcx.def_span(did).clean(cx),
434 visibility: Some(clean::Inherited),
435 stability: tcx.lookup_stability(did).clean(cx),
436 deprecation: tcx.lookup_deprecation(did).clean(cx),
441 fn build_module(cx: &DocContext, did: DefId, visited: &mut FxHashSet<DefId>) -> clean::Module {
442 let mut items = Vec::new();
443 fill_in(cx, did, &mut items, visited);
444 return clean::Module {
449 fn fill_in(cx: &DocContext, did: DefId, items: &mut Vec<clean::Item>,
450 visited: &mut FxHashSet<DefId>) {
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 let def_id = item.def.def_id();
456 if item.vis == ty::Visibility::Public {
457 if did == def_id || !visited.insert(def_id) { continue }
458 if let Some(i) = try_inline(cx, item.def, item.ident.name, visited) {
466 pub fn print_inlined_const(cx: &DocContext, did: DefId) -> String {
467 cx.tcx.rendered_const(did)
470 fn build_const(cx: &DocContext, did: DefId) -> clean::Constant {
472 type_: cx.tcx.type_of(did).clean(cx),
473 expr: print_inlined_const(cx, did)
477 fn build_static(cx: &DocContext, did: DefId, mutable: bool) -> clean::Static {
479 type_: cx.tcx.type_of(did).clean(cx),
480 mutability: if mutable {clean::Mutable} else {clean::Immutable},
481 expr: "\n\n\n".to_string(), // trigger the "[definition]" links
485 fn build_macro(cx: &DocContext, did: DefId, name: ast::Name) -> Option<clean::Macro> {
486 let imported_from = cx.tcx.original_crate_name(did.krate);
487 let def = match cx.cstore.load_macro_untracked(did, cx.sess()) {
488 LoadedMacro::MacroDef(macro_def) => macro_def,
489 // FIXME(jseyfried): document proc macro re-exports
490 LoadedMacro::ProcMacro(..) => return None,
493 let matchers: hir::HirVec<Span> = if let ast::ItemKind::MacroDef(ref def) = def.node {
494 let tts: Vec<_> = def.stream().into_trees().collect();
495 tts.chunks(4).map(|arm| arm[0].span()).collect()
500 let source = format!("macro_rules! {} {{\n{}}}",
502 matchers.iter().map(|span| {
503 format!(" {} => {{ ... }};\n", span.to_src(cx))
504 }).collect::<String>());
508 imported_from: Some(imported_from).clean(cx),
512 /// A trait's generics clause actually contains all of the predicates for all of
513 /// its associated types as well. We specifically move these clauses to the
514 /// associated types instead when displaying, so when we're generating the
515 /// generics for the trait itself we need to be sure to remove them.
516 /// We also need to remove the implied "recursive" Self: Trait bound.
518 /// The inverse of this filtering logic can be found in the `Clean`
519 /// implementation for `AssociatedType`
520 fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean::Generics {
521 for pred in &mut g.where_predicates {
523 clean::WherePredicate::BoundPredicate {
524 ty: clean::Generic(ref s),
526 } if *s == "Self" => {
527 bounds.retain(|bound| {
529 clean::GenericBound::TraitBound(clean::PolyTrait {
530 trait_: clean::ResolvedPath { did, .. },
532 }, _) => did != trait_did,
541 g.where_predicates.retain(|pred| {
543 clean::WherePredicate::BoundPredicate {
545 self_type: box clean::Generic(ref s),
546 trait_: box clean::ResolvedPath { did, .. },
549 } => !(*s == "Self" && did == trait_did) && !bounds.is_empty(),
556 /// Supertrait bounds for a trait are also listed in the generics coming from
557 /// the metadata for a crate, so we want to separate those out and create a new
558 /// list of explicit supertrait bounds to render nicely.
559 fn separate_supertrait_bounds(mut g: clean::Generics)
560 -> (clean::Generics, Vec<clean::GenericBound>) {
561 let mut ty_bounds = Vec::new();
562 g.where_predicates.retain(|pred| {
564 clean::WherePredicate::BoundPredicate {
565 ty: clean::Generic(ref s),
567 } if *s == "Self" => {
568 ty_bounds.extend(bounds.iter().cloned());
577 pub fn record_extern_trait(cx: &DocContext, did: DefId) {
578 if cx.external_traits.borrow().contains_key(&did) ||
579 cx.active_extern_traits.borrow().contains(&did)
584 cx.active_extern_traits.borrow_mut().push(did);
586 let trait_ = build_external_trait(cx, did);
588 cx.external_traits.borrow_mut().insert(did, trait_);
589 cx.active_extern_traits.borrow_mut().remove_item(&did);