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))
100 // Macros are eagerly inlined back in visit_ast, don't show their export statements
101 // FIXME(50647): the eager inline does not take doc(hidden)/doc(no_inline) into account
102 Def::Macro(..) => return Some(Vec::new()),
105 cx.renderinfo.borrow_mut().inlined.insert(did);
106 ret.push(clean::Item {
107 source: cx.tcx.def_span(did).clean(cx),
108 name: Some(name.clean(cx)),
109 attrs: load_attrs(cx, did),
111 visibility: Some(clean::Public),
112 stability: cx.tcx.lookup_stability(did).clean(cx),
113 deprecation: cx.tcx.lookup_deprecation(did).clean(cx),
119 pub fn try_inline_glob(cx: &DocContext, def: Def, visited: &mut FxHashSet<DefId>)
120 -> Option<Vec<clean::Item>>
122 if def == Def::Err { return None }
123 let did = def.def_id();
124 if did.is_local() { return None }
128 let m = build_module(cx, did, visited);
131 // glob imports on things like enums aren't inlined even for local exports, so just bail
136 pub fn load_attrs(cx: &DocContext, did: DefId) -> clean::Attributes {
137 cx.tcx.get_attrs(did).clean(cx)
140 /// Record an external fully qualified name in the external_paths cache.
142 /// These names are used later on by HTML rendering to generate things like
143 /// source links back to the original item.
144 pub fn record_extern_fqn(cx: &DocContext, did: DefId, kind: clean::TypeKind) {
146 debug!("record_extern_fqn(did={:?}, kind+{:?}): def_id is local, aborting", did, kind);
150 let crate_name = cx.tcx.crate_name(did.krate).to_string();
151 let relative = cx.tcx.def_path(did).data.into_iter().filter_map(|elem| {
152 // extern blocks have an empty name
153 let s = elem.data.to_string();
160 let fqn = if let clean::TypeKind::Macro = kind {
161 vec![crate_name, relative.last().unwrap()]
163 once(crate_name).chain(relative).collect()
165 cx.renderinfo.borrow_mut().external_paths.insert(did, (fqn, kind));
168 pub fn build_external_trait(cx: &DocContext, did: DefId) -> clean::Trait {
169 let auto_trait = cx.tcx.trait_def(did).has_auto_impl;
170 let trait_items = cx.tcx.associated_items(did).map(|item| item.clean(cx)).collect();
171 let predicates = cx.tcx.predicates_of(did);
172 let generics = (cx.tcx.generics_of(did), &predicates).clean(cx);
173 let generics = filter_non_trait_generics(did, generics);
174 let (generics, supertrait_bounds) = separate_supertrait_bounds(generics);
175 let is_spotlight = load_attrs(cx, did).has_doc_flag("spotlight");
176 let is_auto = cx.tcx.trait_is_auto(did);
179 unsafety: cx.tcx.trait_def(did).unsafety,
182 bounds: supertrait_bounds,
188 fn build_external_function(cx: &DocContext, did: DefId) -> clean::Function {
189 let sig = cx.tcx.fn_sig(did);
191 let constness = if cx.tcx.is_const_fn(did) {
192 hir::Constness::Const
194 hir::Constness::NotConst
197 let predicates = cx.tcx.predicates_of(did);
199 decl: (did, sig).clean(cx),
200 generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
201 header: hir::FnHeader {
202 unsafety: sig.unsafety(),
205 asyncness: hir::IsAsync::NotAsync,
210 fn build_enum(cx: &DocContext, did: DefId) -> clean::Enum {
211 let predicates = cx.tcx.predicates_of(did);
214 generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
215 variants_stripped: false,
216 variants: cx.tcx.adt_def(did).variants.clean(cx),
220 fn build_struct(cx: &DocContext, did: DefId) -> clean::Struct {
221 let predicates = cx.tcx.predicates_of(did);
222 let variant = cx.tcx.adt_def(did).non_enum_variant();
225 struct_type: match variant.ctor_kind {
226 CtorKind::Fictive => doctree::Plain,
227 CtorKind::Fn => doctree::Tuple,
228 CtorKind::Const => doctree::Unit,
230 generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
231 fields: variant.fields.clean(cx),
232 fields_stripped: false,
236 fn build_union(cx: &DocContext, did: DefId) -> clean::Union {
237 let predicates = cx.tcx.predicates_of(did);
238 let variant = cx.tcx.adt_def(did).non_enum_variant();
241 struct_type: doctree::Plain,
242 generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
243 fields: variant.fields.clean(cx),
244 fields_stripped: false,
248 fn build_type_alias(cx: &DocContext, did: DefId) -> clean::Typedef {
249 let predicates = cx.tcx.predicates_of(did);
252 type_: cx.tcx.type_of(did).clean(cx),
253 generics: (cx.tcx.generics_of(did), &predicates).clean(cx),
257 pub fn build_impls(cx: &DocContext, did: DefId, auto_traits: bool) -> Vec<clean::Item> {
259 let mut impls = Vec::new();
261 for &did in tcx.inherent_impls(did).iter() {
262 build_impl(cx, did, &mut impls);
266 let auto_impls = get_auto_traits_with_def_id(cx, did);
267 let mut renderinfo = cx.renderinfo.borrow_mut();
269 let new_impls: Vec<clean::Item> = auto_impls.into_iter()
270 .filter(|i| renderinfo.inlined.insert(i.def_id)).collect();
272 impls.extend(new_impls);
275 // If this is the first time we've inlined something from another crate, then
276 // we inline *all* impls from all the crates into this crate. Note that there's
277 // currently no way for us to filter this based on type, and we likely need
278 // many impls for a variety of reasons.
280 // Primarily, the impls will be used to populate the documentation for this
281 // type being inlined, but impls can also be used when generating
282 // documentation for primitives (no way to find those specifically).
283 if cx.populated_all_crate_impls.get() {
287 cx.populated_all_crate_impls.set(true);
289 for &cnum in tcx.crates().iter() {
290 for did in tcx.all_trait_implementations(cnum).iter() {
291 build_impl(cx, *did, &mut impls);
295 // Also try to inline primitive impls from other crates.
296 let lang_items = tcx.lang_items();
297 let primitive_impls = [
298 lang_items.isize_impl(),
299 lang_items.i8_impl(),
300 lang_items.i16_impl(),
301 lang_items.i32_impl(),
302 lang_items.i64_impl(),
303 lang_items.i128_impl(),
304 lang_items.usize_impl(),
305 lang_items.u8_impl(),
306 lang_items.u16_impl(),
307 lang_items.u32_impl(),
308 lang_items.u64_impl(),
309 lang_items.u128_impl(),
310 lang_items.f32_impl(),
311 lang_items.f64_impl(),
312 lang_items.f32_runtime_impl(),
313 lang_items.f64_runtime_impl(),
314 lang_items.char_impl(),
315 lang_items.str_impl(),
316 lang_items.slice_impl(),
317 lang_items.slice_u8_impl(),
318 lang_items.str_alloc_impl(),
319 lang_items.slice_alloc_impl(),
320 lang_items.slice_u8_alloc_impl(),
321 lang_items.const_ptr_impl(),
322 lang_items.mut_ptr_impl(),
325 for def_id in primitive_impls.iter().filter_map(|&def_id| def_id) {
326 if !def_id.is_local() {
327 build_impl(cx, def_id, &mut impls);
329 let auto_impls = get_auto_traits_with_def_id(cx, def_id);
330 let mut renderinfo = cx.renderinfo.borrow_mut();
332 let new_impls: Vec<clean::Item> = auto_impls.into_iter()
333 .filter(|i| renderinfo.inlined.insert(i.def_id)).collect();
335 impls.extend(new_impls);
342 pub fn build_impl(cx: &DocContext, did: DefId, ret: &mut Vec<clean::Item>) {
343 if !cx.renderinfo.borrow_mut().inlined.insert(did) {
347 let attrs = load_attrs(cx, did);
349 let associated_trait = tcx.impl_trait_ref(did);
351 // Only inline impl if the implemented trait is
352 // reachable in rustdoc generated documentation
353 if let Some(traitref) = associated_trait {
354 if !cx.access_levels.borrow().is_doc_reachable(traitref.def_id) {
359 let for_ = tcx.type_of(did).clean(cx);
361 // Only inline impl if the implementing type is
362 // reachable in rustdoc generated documentation
363 if let Some(did) = for_.def_id() {
364 if !cx.access_levels.borrow().is_doc_reachable(did) {
369 let predicates = tcx.predicates_of(did);
370 let trait_items = tcx.associated_items(did).filter_map(|item| {
371 if associated_trait.is_some() || item.vis == ty::Visibility::Public {
376 }).collect::<Vec<_>>();
377 let polarity = tcx.impl_polarity(did);
378 let trait_ = associated_trait.clean(cx).map(|bound| {
380 clean::GenericBound::TraitBound(polyt, _) => polyt.trait_,
381 clean::GenericBound::Outlives(..) => unreachable!(),
384 if trait_.def_id() == tcx.lang_items().deref_trait() {
385 super::build_deref_target_impls(cx, &trait_items, ret);
387 if let Some(trait_did) = trait_.def_id() {
388 record_extern_trait(cx, trait_did);
391 let provided = trait_.def_id().map(|did| {
392 tcx.provided_trait_methods(did)
394 .map(|meth| meth.ident.to_string())
396 }).unwrap_or(FxHashSet());
398 ret.push(clean::Item {
399 inner: clean::ImplItem(clean::Impl {
400 unsafety: hir::Unsafety::Normal,
401 generics: (tcx.generics_of(did), &predicates).clean(cx),
402 provided_trait_methods: provided,
406 polarity: Some(polarity.clean(cx)),
409 source: tcx.def_span(did).clean(cx),
412 visibility: Some(clean::Inherited),
413 stability: tcx.lookup_stability(did).clean(cx),
414 deprecation: tcx.lookup_deprecation(did).clean(cx),
419 fn build_module(cx: &DocContext, did: DefId, visited: &mut FxHashSet<DefId>) -> clean::Module {
420 let mut items = Vec::new();
421 fill_in(cx, did, &mut items, visited);
422 return clean::Module {
427 fn fill_in(cx: &DocContext, did: DefId, items: &mut Vec<clean::Item>,
428 visited: &mut FxHashSet<DefId>) {
429 // If we're re-exporting a re-export it may actually re-export something in
430 // two namespaces, so the target may be listed twice. Make sure we only
431 // visit each node at most once.
432 for &item in cx.tcx.item_children(did).iter() {
433 let def_id = item.def.def_id();
434 if item.vis == ty::Visibility::Public {
435 if did == def_id || !visited.insert(def_id) { continue }
436 if let Some(i) = try_inline(cx, item.def, item.ident.name, visited) {
444 pub fn print_inlined_const(cx: &DocContext, did: DefId) -> String {
445 cx.tcx.rendered_const(did)
448 fn build_const(cx: &DocContext, did: DefId) -> clean::Constant {
450 type_: cx.tcx.type_of(did).clean(cx),
451 expr: print_inlined_const(cx, did)
455 fn build_static(cx: &DocContext, did: DefId, mutable: bool) -> clean::Static {
457 type_: cx.tcx.type_of(did).clean(cx),
458 mutability: if mutable {clean::Mutable} else {clean::Immutable},
459 expr: "\n\n\n".to_string(), // trigger the "[definition]" links
463 /// A trait's generics clause actually contains all of the predicates for all of
464 /// its associated types as well. We specifically move these clauses to the
465 /// associated types instead when displaying, so when we're generating the
466 /// generics for the trait itself we need to be sure to remove them.
467 /// We also need to remove the implied "recursive" Self: Trait bound.
469 /// The inverse of this filtering logic can be found in the `Clean`
470 /// implementation for `AssociatedType`
471 fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean::Generics {
472 for pred in &mut g.where_predicates {
474 clean::WherePredicate::BoundPredicate {
475 ty: clean::Generic(ref s),
477 } if *s == "Self" => {
478 bounds.retain(|bound| {
480 clean::GenericBound::TraitBound(clean::PolyTrait {
481 trait_: clean::ResolvedPath { did, .. },
483 }, _) => did != trait_did,
492 g.where_predicates.retain(|pred| {
494 clean::WherePredicate::BoundPredicate {
496 self_type: box clean::Generic(ref s),
497 trait_: box clean::ResolvedPath { did, .. },
500 } => !(*s == "Self" && did == trait_did) && !bounds.is_empty(),
507 /// Supertrait bounds for a trait are also listed in the generics coming from
508 /// the metadata for a crate, so we want to separate those out and create a new
509 /// list of explicit supertrait bounds to render nicely.
510 fn separate_supertrait_bounds(mut g: clean::Generics)
511 -> (clean::Generics, Vec<clean::GenericBound>) {
512 let mut ty_bounds = Vec::new();
513 g.where_predicates.retain(|pred| {
515 clean::WherePredicate::BoundPredicate {
516 ty: clean::Generic(ref s),
518 } if *s == "Self" => {
519 ty_bounds.extend(bounds.iter().cloned());
528 pub fn record_extern_trait(cx: &DocContext, did: DefId) {
529 if cx.external_traits.borrow().contains_key(&did) ||
530 cx.active_extern_traits.borrow().contains(&did)
535 cx.active_extern_traits.borrow_mut().push(did);
537 let trait_ = build_external_trait(cx, did);
539 cx.external_traits.borrow_mut().insert(did, trait_);
540 cx.active_extern_traits.borrow_mut().remove_item(&did);