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.
13 use std::collections::HashSet;
17 use syntax::attr::AttrMetaMethods;
20 use rustc::middle::cstore::{self, CrateStore};
21 use rustc::hir::def::Def;
22 use rustc::hir::def_id::DefId;
23 use rustc::ty::{self, TyCtxt};
25 use rustc::middle::stability;
27 use rustc_const_eval::lookup_const_by_id;
29 use core::{DocContext, DocAccessLevels};
31 use clean::{self, GetDefId};
33 use super::{Clean, ToSource};
35 /// Attempt to inline the definition of a local node id into this AST.
37 /// This function will fetch the definition of the id specified, and if it is
38 /// from another crate it will attempt to inline the documentation from the
39 /// other crate into this crate.
41 /// This is primarily used for `pub use` statements which are, in general,
42 /// implementation details. Inlining the documentation should help provide a
43 /// better experience when reading the documentation in this use case.
45 /// The returned value is `None` if the `id` could not be inlined, and `Some`
46 /// of a vector of items if it was successfully expanded.
47 pub fn try_inline(cx: &DocContext, id: ast::NodeId, into: Option<ast::Name>)
48 -> Option<Vec<clean::Item>> {
49 let tcx = match cx.tcx_opt() {
53 let def = match tcx.def_map.borrow().get(&id) {
54 Some(d) => d.full_def(),
57 let did = def.def_id();
58 if did.is_local() { return None }
59 try_inline_def(cx, tcx, def).map(|vec| {
60 vec.into_iter().map(|mut item| {
62 Some(into) if item.name.is_some() => {
63 item.name = Some(into.clean(cx));
72 fn try_inline_def(cx: &DocContext, tcx: &TyCtxt,
73 def: Def) -> Option<Vec<clean::Item>> {
74 let mut ret = Vec::new();
75 let did = def.def_id();
76 let inner = match def {
78 record_extern_fqn(cx, did, clean::TypeTrait);
79 clean::TraitItem(build_external_trait(cx, tcx, did))
82 record_extern_fqn(cx, did, clean::TypeFunction);
83 clean::FunctionItem(build_external_function(cx, tcx, did))
86 // If this is a struct constructor, we skip it
87 if tcx.sess.cstore.tuple_struct_definition_if_ctor(did).is_none() => {
88 record_extern_fqn(cx, did, clean::TypeStruct);
89 ret.extend(build_impls(cx, tcx, did));
90 clean::StructItem(build_struct(cx, tcx, did))
92 Def::TyAlias(did) => {
93 record_extern_fqn(cx, did, clean::TypeTypedef);
94 ret.extend(build_impls(cx, tcx, did));
95 build_type(cx, tcx, did)
98 record_extern_fqn(cx, did, clean::TypeEnum);
99 ret.extend(build_impls(cx, tcx, did));
100 build_type(cx, tcx, did)
102 // Assume that the enum type is reexported next to the variant, and
103 // variants don't show up in documentation specially.
104 Def::Variant(..) => return Some(Vec::new()),
106 record_extern_fqn(cx, did, clean::TypeModule);
107 clean::ModuleItem(build_module(cx, tcx, did))
109 Def::Static(did, mtbl) => {
110 record_extern_fqn(cx, did, clean::TypeStatic);
111 clean::StaticItem(build_static(cx, tcx, did, mtbl))
113 Def::Const(did) | Def::AssociatedConst(did) => {
114 record_extern_fqn(cx, did, clean::TypeConst);
115 clean::ConstantItem(build_const(cx, tcx, did))
119 cx.renderinfo.borrow_mut().inlined.insert(did);
120 ret.push(clean::Item {
121 source: clean::Span::empty(),
122 name: Some(tcx.item_name(did).to_string()),
123 attrs: load_attrs(cx, tcx, did),
125 visibility: Some(clean::Public),
126 stability: stability::lookup_stability(tcx, did).clean(cx),
127 deprecation: stability::lookup_deprecation(tcx, did).clean(cx),
133 pub fn load_attrs(cx: &DocContext, tcx: &TyCtxt,
134 did: DefId) -> Vec<clean::Attribute> {
135 tcx.get_attrs(did).iter().map(|a| a.clean(cx)).collect()
138 /// Record an external fully qualified name in the external_paths cache.
140 /// These names are used later on by HTML rendering to generate things like
141 /// source links back to the original item.
142 pub fn record_extern_fqn(cx: &DocContext, did: DefId, kind: clean::TypeKind) {
143 if let Some(tcx) = cx.tcx_opt() {
144 let crate_name = tcx.sess.cstore.crate_name(did.krate).to_string();
145 let relative = tcx.def_path(did).data.into_iter().map(|elem| {
146 elem.data.to_string()
148 let fqn = once(crate_name).chain(relative).collect();
149 cx.renderinfo.borrow_mut().external_paths.insert(did, (fqn, kind));
153 pub fn build_external_trait(cx: &DocContext, tcx: &TyCtxt,
154 did: DefId) -> clean::Trait {
155 let def = tcx.lookup_trait_def(did);
156 let trait_items = tcx.trait_items(did).clean(cx);
157 let predicates = tcx.lookup_predicates(did);
158 let generics = (&def.generics, &predicates, subst::TypeSpace).clean(cx);
159 let generics = filter_non_trait_generics(did, generics);
160 let (generics, supertrait_bounds) = separate_supertrait_bounds(generics);
162 unsafety: def.unsafety,
165 bounds: supertrait_bounds,
169 fn build_external_function(cx: &DocContext, tcx: &TyCtxt, did: DefId) -> clean::Function {
170 let t = tcx.lookup_item_type(did);
171 let (decl, style, abi) = match t.ty.sty {
172 ty::TyFnDef(_, _, ref f) => ((did, &f.sig).clean(cx), f.unsafety, f.abi),
173 _ => panic!("bad function"),
176 let constness = if tcx.sess.cstore.is_const_fn(did) {
177 hir::Constness::Const
179 hir::Constness::NotConst
182 let predicates = tcx.lookup_predicates(did);
185 generics: (&t.generics, &predicates, subst::FnSpace).clean(cx),
187 constness: constness,
192 fn build_struct(cx: &DocContext, tcx: &TyCtxt, did: DefId) -> clean::Struct {
193 let t = tcx.lookup_item_type(did);
194 let predicates = tcx.lookup_predicates(did);
195 let variant = tcx.lookup_adt_def(did).struct_variant();
198 struct_type: match &*variant.fields {
200 [_] if variant.kind == ty::VariantKind::Tuple => doctree::Newtype,
201 [..] if variant.kind == ty::VariantKind::Tuple => doctree::Tuple,
204 generics: (&t.generics, &predicates, subst::TypeSpace).clean(cx),
205 fields: variant.fields.clean(cx),
206 fields_stripped: false,
210 fn build_type(cx: &DocContext, tcx: &TyCtxt, did: DefId) -> clean::ItemEnum {
211 let t = tcx.lookup_item_type(did);
212 let predicates = tcx.lookup_predicates(did);
214 ty::TyEnum(edef, _) if !tcx.sess.cstore.is_typedef(did) => {
215 return clean::EnumItem(clean::Enum {
216 generics: (&t.generics, &predicates, subst::TypeSpace).clean(cx),
217 variants_stripped: false,
218 variants: edef.variants.clean(cx),
224 clean::TypedefItem(clean::Typedef {
225 type_: t.ty.clean(cx),
226 generics: (&t.generics, &predicates, subst::TypeSpace).clean(cx),
230 pub fn build_impls(cx: &DocContext,
232 did: DefId) -> Vec<clean::Item> {
233 tcx.populate_inherent_implementations_for_type_if_necessary(did);
234 let mut impls = Vec::new();
236 if let Some(i) = tcx.inherent_impls.borrow().get(&did) {
237 for &did in i.iter() {
238 build_impl(cx, tcx, did, &mut impls);
242 // If this is the first time we've inlined something from this crate, then
243 // we inline *all* impls from the crate into this crate. Note that there's
244 // currently no way for us to filter this based on type, and we likely need
245 // many impls for a variety of reasons.
247 // Primarily, the impls will be used to populate the documentation for this
248 // type being inlined, but impls can also be used when generating
249 // documentation for primitives (no way to find those specifically).
250 if !cx.all_crate_impls.borrow_mut().contains_key(&did.krate) {
251 let mut impls = Vec::new();
252 for item in tcx.sess.cstore.crate_top_level_items(did.krate) {
253 populate_impls(cx, tcx, item.def, &mut impls);
255 cx.all_crate_impls.borrow_mut().insert(did.krate, impls);
257 fn populate_impls(cx: &DocContext, tcx: &TyCtxt,
258 def: cstore::DefLike,
259 impls: &mut Vec<clean::Item>) {
261 cstore::DlImpl(did) => build_impl(cx, tcx, did, impls),
262 cstore::DlDef(Def::Mod(did)) => {
263 for item in tcx.sess.cstore.item_children(did) {
264 populate_impls(cx, tcx, item.def, impls)
272 let mut candidates = cx.all_crate_impls.borrow_mut();
273 let candidates = candidates.get_mut(&did.krate).unwrap();
274 for i in (0..candidates.len()).rev() {
275 let remove = match candidates[i].inner {
276 clean::ImplItem(ref i) => {
277 i.for_.def_id() == Some(did) || i.for_.primitive_type().is_some()
282 impls.push(candidates.swap_remove(i));
289 pub fn build_impl(cx: &DocContext,
292 ret: &mut Vec<clean::Item>) {
293 if !cx.renderinfo.borrow_mut().inlined.insert(did) {
297 let attrs = load_attrs(cx, tcx, did);
298 let associated_trait = tcx.impl_trait_ref(did);
300 // Only inline impl if the implemented trait is
301 // reachable in rustdoc generated documentation
302 if let Some(traitref) = associated_trait {
303 if !cx.access_levels.borrow().is_doc_reachable(traitref.def_id) {
308 // If this is a defaulted impl, then bail out early here
309 if tcx.sess.cstore.is_default_impl(did) {
310 return ret.push(clean::Item {
311 inner: clean::DefaultImplItem(clean::DefaultImpl {
312 // FIXME: this should be decoded
313 unsafety: hir::Unsafety::Normal,
314 trait_: match associated_trait.as_ref().unwrap().clean(cx) {
315 clean::TraitBound(polyt, _) => polyt.trait_,
316 clean::RegionBound(..) => unreachable!(),
319 source: clean::Span::empty(),
322 visibility: Some(clean::Inherited),
323 stability: stability::lookup_stability(tcx, did).clean(cx),
324 deprecation: stability::lookup_deprecation(tcx, did).clean(cx),
329 let ty = tcx.lookup_item_type(did);
330 let for_ = ty.ty.clean(cx);
332 // Only inline impl if the implementing type is
333 // reachable in rustdoc generated documentation
334 if let Some(did) = for_.def_id() {
335 if !cx.access_levels.borrow().is_doc_reachable(did) {
340 let predicates = tcx.lookup_predicates(did);
341 let trait_items = tcx.sess.cstore.impl_items(did)
344 let did = did.def_id();
345 let impl_item = tcx.impl_or_trait_item(did);
347 ty::ConstTraitItem(ref assoc_const) => {
348 let did = assoc_const.def_id;
349 let type_scheme = tcx.lookup_item_type(did);
350 let default = if assoc_const.has_value {
351 Some(lookup_const_by_id(tcx, did, None)
352 .unwrap().0.span.to_src(cx))
357 name: Some(assoc_const.name.clean(cx)),
358 inner: clean::AssociatedConstItem(
359 type_scheme.ty.clean(cx),
362 source: clean::Span::empty(),
365 stability: stability::lookup_stability(tcx, did).clean(cx),
366 deprecation: stability::lookup_deprecation(tcx, did).clean(cx),
370 ty::MethodTraitItem(method) => {
371 if method.vis != ty::Visibility::Public && associated_trait.is_none() {
374 let mut item = method.clean(cx);
375 item.inner = match item.inner.clone() {
376 clean::TyMethodItem(clean::TyMethod {
377 unsafety, decl, self_, generics, abi
379 let constness = if tcx.sess.cstore.is_const_fn(did) {
380 hir::Constness::Const
382 hir::Constness::NotConst
385 clean::MethodItem(clean::Method {
387 constness: constness,
394 _ => panic!("not a tymethod"),
398 ty::TypeTraitItem(ref assoc_ty) => {
399 let did = assoc_ty.def_id;
400 let type_scheme = ty::TypeScheme {
401 ty: assoc_ty.ty.unwrap(),
402 generics: ty::Generics::empty()
404 // Not sure the choice of ParamSpace actually matters here,
405 // because an associated type won't have generics on the LHS
406 let typedef = (type_scheme, ty::GenericPredicates::empty(),
407 subst::ParamSpace::TypeSpace).clean(cx);
409 name: Some(assoc_ty.name.clean(cx)),
410 inner: clean::TypedefItem(typedef, true),
411 source: clean::Span::empty(),
414 stability: stability::lookup_stability(tcx, did).clean(cx),
415 deprecation: stability::lookup_deprecation(tcx, did).clean(cx),
420 }).collect::<Vec<_>>();
421 let polarity = tcx.trait_impl_polarity(did);
422 let trait_ = associated_trait.clean(cx).map(|bound| {
424 clean::TraitBound(polyt, _) => polyt.trait_,
425 clean::RegionBound(..) => unreachable!(),
428 if trait_.def_id() == cx.deref_trait_did.get() {
429 super::build_deref_target_impls(cx, &trait_items, ret);
432 let provided = trait_.def_id().map(|did| {
433 cx.tcx().provided_trait_methods(did)
435 .map(|meth| meth.name.to_string())
437 }).unwrap_or(HashSet::new());
439 ret.push(clean::Item {
440 inner: clean::ImplItem(clean::Impl {
441 unsafety: hir::Unsafety::Normal, // FIXME: this should be decoded
442 derived: clean::detect_derived(&attrs),
443 provided_trait_methods: provided,
446 generics: (&ty.generics, &predicates, subst::TypeSpace).clean(cx),
448 polarity: polarity.map(|p| { p.clean(cx) }),
450 source: clean::Span::empty(),
453 visibility: Some(clean::Inherited),
454 stability: stability::lookup_stability(tcx, did).clean(cx),
455 deprecation: stability::lookup_deprecation(tcx, did).clean(cx),
460 fn build_module(cx: &DocContext, tcx: &TyCtxt,
461 did: DefId) -> clean::Module {
462 let mut items = Vec::new();
463 fill_in(cx, tcx, did, &mut items);
464 return clean::Module {
469 fn fill_in(cx: &DocContext, tcx: &TyCtxt, did: DefId,
470 items: &mut Vec<clean::Item>) {
471 // If we're reexporting a reexport it may actually reexport something in
472 // two namespaces, so the target may be listed twice. Make sure we only
473 // visit each node at most once.
474 let mut visited = HashSet::new();
475 for item in tcx.sess.cstore.item_children(did) {
477 cstore::DlDef(Def::ForeignMod(did)) => {
478 fill_in(cx, tcx, did, items);
480 cstore::DlDef(def) if item.vis == ty::Visibility::Public => {
481 if !visited.insert(def) { continue }
482 if let Some(i) = try_inline_def(cx, tcx, def) {
486 cstore::DlDef(..) => {}
487 // All impls were inlined above
488 cstore::DlImpl(..) => {}
489 cstore::DlField => panic!("unimplemented field"),
495 fn build_const(cx: &DocContext, tcx: &TyCtxt,
496 did: DefId) -> clean::Constant {
497 use rustc::hir::print as pprust;
499 let (expr, ty) = lookup_const_by_id(tcx, did, None).unwrap_or_else(|| {
500 panic!("expected lookup_const_by_id to succeed for {:?}", did);
502 debug!("converting constant expr {:?} to snippet", expr);
503 let sn = pprust::expr_to_string(expr);
504 debug!("got snippet {}", sn);
507 type_: ty.map(|t| t.clean(cx)).unwrap_or_else(|| tcx.lookup_item_type(did).ty.clean(cx)),
512 fn build_static(cx: &DocContext, tcx: &TyCtxt,
514 mutable: bool) -> clean::Static {
516 type_: tcx.lookup_item_type(did).ty.clean(cx),
517 mutability: if mutable {clean::Mutable} else {clean::Immutable},
518 expr: "\n\n\n".to_string(), // trigger the "[definition]" links
522 /// A trait's generics clause actually contains all of the predicates for all of
523 /// its associated types as well. We specifically move these clauses to the
524 /// associated types instead when displaying, so when we're genering the
525 /// generics for the trait itself we need to be sure to remove them.
527 /// The inverse of this filtering logic can be found in the `Clean`
528 /// implementation for `AssociatedType`
529 fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics)
531 g.where_predicates.retain(|pred| {
533 clean::WherePredicate::BoundPredicate {
535 self_type: box clean::Generic(ref s),
536 trait_: box clean::ResolvedPath { did, .. },
539 } => *s != "Self" || did != trait_did,
546 /// Supertrait bounds for a trait are also listed in the generics coming from
547 /// the metadata for a crate, so we want to separate those out and create a new
548 /// list of explicit supertrait bounds to render nicely.
549 fn separate_supertrait_bounds(mut g: clean::Generics)
550 -> (clean::Generics, Vec<clean::TyParamBound>) {
551 let mut ty_bounds = Vec::new();
552 g.where_predicates.retain(|pred| {
554 clean::WherePredicate::BoundPredicate {
555 ty: clean::Generic(ref s),
557 } if *s == "Self" => {
558 ty_bounds.extend(bounds.iter().cloned());