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.
18 use rustc::hir::def::{Def, CtorKind};
19 use rustc::hir::def_id::DefId;
21 use rustc::util::nodemap::FxHashSet;
23 use core::{DocContext, DocAccessLevels};
25 use clean::{self, GetDefId, get_auto_traits_with_def_id};
29 /// Attempt to inline a definition into this AST.
31 /// This function will fetch the definition specified, and if it is
32 /// from another crate it will attempt to inline the documentation
33 /// from the other crate into this crate.
35 /// This is primarily used for `pub use` statements which are, in general,
36 /// implementation details. Inlining the documentation should help provide a
37 /// better experience when reading the documentation in this use case.
39 /// The returned value is `None` if the definition could not be inlined,
40 /// and `Some` of a vector of items if it was successfully expanded.
41 pub fn try_inline(cx: &DocContext, def: Def, name: ast::Name, visited: &mut FxHashSet<DefId>)
42 -> Option<Vec<clean::Item>> {
43 if def == Def::Err { return None }
44 let did = def.def_id();
45 if did.is_local() { return None }
46 let mut ret = Vec::new();
47 let inner = match def {
49 record_extern_fqn(cx, did, clean::TypeKind::Trait);
50 ret.extend(build_impls(cx, did, false));
51 clean::TraitItem(build_external_trait(cx, did))
54 record_extern_fqn(cx, did, clean::TypeKind::Function);
55 clean::FunctionItem(build_external_function(cx, did))
58 record_extern_fqn(cx, did, clean::TypeKind::Struct);
59 ret.extend(build_impls(cx, did, true));
60 clean::StructItem(build_struct(cx, did))
63 record_extern_fqn(cx, did, clean::TypeKind::Union);
64 ret.extend(build_impls(cx, did, true));
65 clean::UnionItem(build_union(cx, did))
67 Def::TyAlias(did) => {
68 record_extern_fqn(cx, did, clean::TypeKind::Typedef);
69 ret.extend(build_impls(cx, did, false));
70 clean::TypedefItem(build_type_alias(cx, did), false)
73 record_extern_fqn(cx, did, clean::TypeKind::Enum);
74 ret.extend(build_impls(cx, did, true));
75 clean::EnumItem(build_enum(cx, did))
77 Def::TyForeign(did) => {
78 record_extern_fqn(cx, did, clean::TypeKind::Foreign);
79 ret.extend(build_impls(cx, did, false));
80 clean::ForeignTypeItem
82 // Never inline enum variants but leave them shown as re-exports.
83 Def::Variant(..) => return None,
84 // Assume that enum variants and struct types are re-exported next to
85 // their constructors.
86 Def::VariantCtor(..) |
87 Def::StructCtor(..) => return Some(Vec::new()),
89 record_extern_fqn(cx, did, clean::TypeKind::Module);
90 clean::ModuleItem(build_module(cx, did, visited))
92 Def::Static(did, mtbl) => {
93 record_extern_fqn(cx, did, clean::TypeKind::Static);
94 clean::StaticItem(build_static(cx, did, mtbl))
97 record_extern_fqn(cx, did, clean::TypeKind::Const);
98 clean::ConstantItem(build_const(cx, did))
102 cx.renderinfo.borrow_mut().inlined.insert(did);
103 ret.push(clean::Item {
104 source: cx.tcx.def_span(did).clean(cx),
105 name: Some(name.clean(cx)),
106 attrs: load_attrs(cx, did),
108 visibility: Some(clean::Public),
109 stability: cx.tcx.lookup_stability(did).clean(cx),
110 deprecation: cx.tcx.lookup_deprecation(did).clean(cx),
116 pub fn load_attrs(cx: &DocContext, did: DefId) -> clean::Attributes {
117 cx.tcx.get_attrs(did).clean(cx)
120 /// Record an external fully qualified name in the external_paths cache.
122 /// These names are used later on by HTML rendering to generate things like
123 /// source links back to the original item.
124 pub fn record_extern_fqn(cx: &DocContext, did: DefId, kind: clean::TypeKind) {
126 debug!("record_extern_fqn(did={:?}, kind+{:?}): def_id is local, aborting", did, kind);
130 let crate_name = cx.tcx.crate_name(did.krate).to_string();
131 let relative = cx.tcx.def_path(did).data.into_iter().filter_map(|elem| {
132 // extern blocks have an empty name
133 let s = elem.data.to_string();
140 let fqn = if let clean::TypeKind::Macro = kind {
141 vec![crate_name, relative.last().unwrap()]
143 once(crate_name).chain(relative).collect()
145 cx.renderinfo.borrow_mut().external_paths.insert(did, (fqn, kind));
148 pub fn build_external_trait(cx: &DocContext, did: DefId) -> clean::Trait {
149 let auto_trait = cx.tcx.trait_def(did).has_auto_impl;
150 let trait_items = cx.tcx.associated_items(did).map(|item| item.clean(cx)).collect();
151 let predicates = cx.tcx.predicates_of(did);
152 let generics = (cx.tcx.generics_of(did), &predicates).clean(cx);
153 let generics = filter_non_trait_generics(did, generics);
154 let (generics, supertrait_bounds) = separate_supertrait_bounds(generics);
155 let is_spotlight = load_attrs(cx, did).has_doc_flag("spotlight");
156 let is_auto = cx.tcx.trait_is_auto(did);
159 unsafety: cx.tcx.trait_def(did).unsafety,
162 bounds: supertrait_bounds,
168 fn build_external_function(cx: &DocContext, did: DefId) -> clean::Function {
169 let sig = cx.tcx.fn_sig(did);
171 let constness = if cx.tcx.is_const_fn(did) {
172 hir::Constness::Const
174 hir::Constness::NotConst
177 let predicates = cx.tcx.predicates_of(did);
179 decl: (did, sig).clean(cx),
180 generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
181 unsafety: sig.unsafety(),
187 fn build_enum(cx: &DocContext, did: DefId) -> clean::Enum {
188 let predicates = cx.tcx.predicates_of(did);
191 generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
192 variants_stripped: false,
193 variants: cx.tcx.adt_def(did).variants.clean(cx),
197 fn build_struct(cx: &DocContext, did: DefId) -> clean::Struct {
198 let predicates = cx.tcx.predicates_of(did);
199 let variant = cx.tcx.adt_def(did).non_enum_variant();
202 struct_type: match variant.ctor_kind {
203 CtorKind::Fictive => doctree::Plain,
204 CtorKind::Fn => doctree::Tuple,
205 CtorKind::Const => doctree::Unit,
207 generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
208 fields: variant.fields.clean(cx),
209 fields_stripped: false,
213 fn build_union(cx: &DocContext, did: DefId) -> clean::Union {
214 let predicates = cx.tcx.predicates_of(did);
215 let variant = cx.tcx.adt_def(did).non_enum_variant();
218 struct_type: doctree::Plain,
219 generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
220 fields: variant.fields.clean(cx),
221 fields_stripped: false,
225 fn build_type_alias(cx: &DocContext, did: DefId) -> clean::Typedef {
226 let predicates = cx.tcx.predicates_of(did);
229 type_: cx.tcx.type_of(did).clean(cx),
230 generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
234 pub fn build_impls(cx: &DocContext, did: DefId, auto_traits: bool) -> Vec<clean::Item> {
236 let mut impls = Vec::new();
238 for &did in tcx.inherent_impls(did).iter() {
239 build_impl(cx, did, &mut impls);
243 let auto_impls = get_auto_traits_with_def_id(cx, did);
244 let mut renderinfo = cx.renderinfo.borrow_mut();
246 let new_impls: Vec<clean::Item> = auto_impls.into_iter()
247 .filter(|i| renderinfo.inlined.insert(i.def_id)).collect();
249 impls.extend(new_impls);
252 // If this is the first time we've inlined something from another crate, then
253 // we inline *all* impls from all the crates into this crate. Note that there's
254 // currently no way for us to filter this based on type, and we likely need
255 // many impls for a variety of reasons.
257 // Primarily, the impls will be used to populate the documentation for this
258 // type being inlined, but impls can also be used when generating
259 // documentation for primitives (no way to find those specifically).
260 if cx.populated_all_crate_impls.get() {
264 cx.populated_all_crate_impls.set(true);
266 for &cnum in tcx.crates().iter() {
267 for did in tcx.all_trait_implementations(cnum).iter() {
268 build_impl(cx, *did, &mut impls);
272 // Also try to inline primitive impls from other crates.
273 let lang_items = tcx.lang_items();
274 let primitive_impls = [
275 lang_items.isize_impl(),
276 lang_items.i8_impl(),
277 lang_items.i16_impl(),
278 lang_items.i32_impl(),
279 lang_items.i64_impl(),
280 lang_items.i128_impl(),
281 lang_items.usize_impl(),
282 lang_items.u8_impl(),
283 lang_items.u16_impl(),
284 lang_items.u32_impl(),
285 lang_items.u64_impl(),
286 lang_items.u128_impl(),
287 lang_items.f32_impl(),
288 lang_items.f64_impl(),
289 lang_items.f32_runtime_impl(),
290 lang_items.f64_runtime_impl(),
291 lang_items.char_impl(),
292 lang_items.str_impl(),
293 lang_items.slice_impl(),
294 lang_items.slice_u8_impl(),
295 lang_items.str_alloc_impl(),
296 lang_items.slice_alloc_impl(),
297 lang_items.slice_u8_alloc_impl(),
298 lang_items.const_ptr_impl(),
299 lang_items.mut_ptr_impl(),
302 for def_id in primitive_impls.iter().filter_map(|&def_id| def_id) {
303 if !def_id.is_local() {
304 build_impl(cx, def_id, &mut impls);
311 pub fn build_impl(cx: &DocContext, did: DefId, ret: &mut Vec<clean::Item>) {
312 if !cx.renderinfo.borrow_mut().inlined.insert(did) {
316 let attrs = load_attrs(cx, did);
318 let associated_trait = tcx.impl_trait_ref(did);
320 // Only inline impl if the implemented trait is
321 // reachable in rustdoc generated documentation
322 if let Some(traitref) = associated_trait {
323 if !cx.access_levels.borrow().is_doc_reachable(traitref.def_id) {
328 let for_ = tcx.type_of(did).clean(cx);
330 // Only inline impl if the implementing type is
331 // reachable in rustdoc generated documentation
332 if let Some(did) = for_.def_id() {
333 if !cx.access_levels.borrow().is_doc_reachable(did) {
338 let predicates = tcx.predicates_of(did);
339 let trait_items = tcx.associated_items(did).filter_map(|item| {
340 if associated_trait.is_some() || item.vis == ty::Visibility::Public {
345 }).collect::<Vec<_>>();
346 let polarity = tcx.impl_polarity(did);
347 let trait_ = associated_trait.clean(cx).map(|bound| {
349 clean::TraitBound(polyt, _) => polyt.trait_,
350 clean::RegionBound(..) => unreachable!(),
353 if trait_.def_id() == tcx.lang_items().deref_trait() {
354 super::build_deref_target_impls(cx, &trait_items, ret);
356 if let Some(trait_did) = trait_.def_id() {
357 record_extern_trait(cx, trait_did);
360 let provided = trait_.def_id().map(|did| {
361 tcx.provided_trait_methods(did)
363 .map(|meth| meth.name.to_string())
365 }).unwrap_or(FxHashSet());
367 ret.push(clean::Item {
368 inner: clean::ImplItem(clean::Impl {
369 unsafety: hir::Unsafety::Normal,
370 generics: (tcx.generics_of(did), &predicates).clean(cx),
371 provided_trait_methods: provided,
375 polarity: Some(polarity.clean(cx)),
378 source: tcx.def_span(did).clean(cx),
381 visibility: Some(clean::Inherited),
382 stability: tcx.lookup_stability(did).clean(cx),
383 deprecation: tcx.lookup_deprecation(did).clean(cx),
388 fn build_module(cx: &DocContext, did: DefId, visited: &mut FxHashSet<DefId>) -> clean::Module {
389 let mut items = Vec::new();
390 fill_in(cx, did, &mut items, visited);
391 return clean::Module {
396 fn fill_in(cx: &DocContext, did: DefId, items: &mut Vec<clean::Item>,
397 visited: &mut FxHashSet<DefId>) {
398 // If we're re-exporting a re-export it may actually re-export something in
399 // two namespaces, so the target may be listed twice. Make sure we only
400 // visit each node at most once.
401 for &item in cx.tcx.item_children(did).iter() {
402 let def_id = item.def.def_id();
403 if item.vis == ty::Visibility::Public {
404 if did == def_id || !visited.insert(def_id) { continue }
405 if let Some(i) = try_inline(cx, item.def, item.ident.name, visited) {
413 pub fn print_inlined_const(cx: &DocContext, did: DefId) -> String {
414 cx.tcx.rendered_const(did)
417 fn build_const(cx: &DocContext, did: DefId) -> clean::Constant {
419 type_: cx.tcx.type_of(did).clean(cx),
420 expr: print_inlined_const(cx, did)
424 fn build_static(cx: &DocContext, did: DefId, mutable: bool) -> clean::Static {
426 type_: cx.tcx.type_of(did).clean(cx),
427 mutability: if mutable {clean::Mutable} else {clean::Immutable},
428 expr: "\n\n\n".to_string(), // trigger the "[definition]" links
432 /// A trait's generics clause actually contains all of the predicates for all of
433 /// its associated types as well. We specifically move these clauses to the
434 /// associated types instead when displaying, so when we're generating the
435 /// generics for the trait itself we need to be sure to remove them.
436 /// We also need to remove the implied "recursive" Self: Trait bound.
438 /// The inverse of this filtering logic can be found in the `Clean`
439 /// implementation for `AssociatedType`
440 fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean::Generics {
441 for pred in &mut g.where_predicates {
443 clean::WherePredicate::BoundPredicate {
444 ty: clean::Generic(ref s),
446 } if *s == "Self" => {
447 bounds.retain(|bound| {
449 clean::TyParamBound::TraitBound(clean::PolyTrait {
450 trait_: clean::ResolvedPath { did, .. },
452 }, _) => did != trait_did,
461 g.where_predicates.retain(|pred| {
463 clean::WherePredicate::BoundPredicate {
465 self_type: box clean::Generic(ref s),
466 trait_: box clean::ResolvedPath { did, .. },
469 } => !(*s == "Self" && did == trait_did) && !bounds.is_empty(),
476 /// Supertrait bounds for a trait are also listed in the generics coming from
477 /// the metadata for a crate, so we want to separate those out and create a new
478 /// list of explicit supertrait bounds to render nicely.
479 fn separate_supertrait_bounds(mut g: clean::Generics)
480 -> (clean::Generics, Vec<clean::TyParamBound>) {
481 let mut ty_bounds = Vec::new();
482 g.where_predicates.retain(|pred| {
484 clean::WherePredicate::BoundPredicate {
485 ty: clean::Generic(ref s),
487 } if *s == "Self" => {
488 ty_bounds.extend(bounds.iter().cloned());
497 pub fn record_extern_trait(cx: &DocContext, did: DefId) {
498 if cx.external_traits.borrow().contains_key(&did) ||
499 cx.active_extern_traits.borrow().contains(&did)
504 cx.active_extern_traits.borrow_mut().push(did);
506 let trait_ = build_external_trait(cx, did);
508 cx.external_traits.borrow_mut().insert(did, trait_);
509 cx.active_extern_traits.borrow_mut().remove_item(&did);