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;
16 use syntax::attr::AttrMetaMethods;
19 use rustc::metadata::csearch;
20 use rustc::metadata::decoder;
21 use rustc::middle::def;
22 use rustc::middle::def_id::DefId;
23 use rustc::middle::ty;
24 use rustc::middle::subst;
25 use rustc::middle::stability;
26 use rustc::middle::const_eval;
32 use super::{Clean, ToSource};
34 /// Attempt to inline the definition of a local node id into this AST.
36 /// This function will fetch the definition of the id specified, and if it is
37 /// from another crate it will attempt to inline the documentation from the
38 /// other crate into this crate.
40 /// This is primarily used for `pub use` statements which are, in general,
41 /// implementation details. Inlining the documentation should help provide a
42 /// better experience when reading the documentation in this use case.
44 /// The returned value is `None` if the `id` could not be inlined, and `Some`
45 /// of a vector of items if it was successfully expanded.
46 pub fn try_inline(cx: &DocContext, id: ast::NodeId, into: Option<ast::Name>)
47 -> Option<Vec<clean::Item>> {
48 let tcx = match cx.tcx_opt() {
52 let def = match tcx.def_map.borrow().get(&id) {
53 Some(d) => d.full_def(),
56 let did = def.def_id();
57 if did.is_local() { return None }
58 try_inline_def(cx, tcx, def).map(|vec| {
59 vec.into_iter().map(|mut item| {
61 Some(into) if item.name.is_some() => {
62 item.name = Some(into.clean(cx));
71 fn try_inline_def(cx: &DocContext, tcx: &ty::ctxt,
72 def: def::Def) -> Option<Vec<clean::Item>> {
73 let mut ret = Vec::new();
74 let did = def.def_id();
75 let inner = match def {
76 def::DefTrait(did) => {
77 record_extern_fqn(cx, did, clean::TypeTrait);
78 clean::TraitItem(build_external_trait(cx, tcx, did))
80 def::DefFn(did, false) => {
81 // If this function is a tuple struct constructor, we just skip it
82 record_extern_fqn(cx, did, clean::TypeFunction);
83 clean::FunctionItem(build_external_function(cx, tcx, did))
85 def::DefStruct(did) => {
86 record_extern_fqn(cx, did, clean::TypeStruct);
87 ret.extend(build_impls(cx, tcx, did));
88 clean::StructItem(build_struct(cx, tcx, did))
90 def::DefTy(did, false) => {
91 record_extern_fqn(cx, did, clean::TypeTypedef);
92 ret.extend(build_impls(cx, tcx, did));
93 build_type(cx, tcx, did)
95 def::DefTy(did, true) => {
96 record_extern_fqn(cx, did, clean::TypeEnum);
97 ret.extend(build_impls(cx, tcx, did));
98 build_type(cx, tcx, did)
100 // Assume that the enum type is reexported next to the variant, and
101 // variants don't show up in documentation specially.
102 def::DefVariant(..) => return Some(Vec::new()),
103 def::DefMod(did) => {
104 record_extern_fqn(cx, did, clean::TypeModule);
105 clean::ModuleItem(build_module(cx, tcx, did))
107 def::DefStatic(did, mtbl) => {
108 record_extern_fqn(cx, did, clean::TypeStatic);
109 clean::StaticItem(build_static(cx, tcx, did, mtbl))
111 def::DefConst(did) | def::DefAssociatedConst(did) => {
112 record_extern_fqn(cx, did, clean::TypeConst);
113 clean::ConstantItem(build_const(cx, tcx, did))
117 cx.inlined.borrow_mut().as_mut().unwrap().insert(did);
118 ret.push(clean::Item {
119 source: clean::Span::empty(),
120 name: Some(tcx.item_name(did).to_string()),
121 attrs: load_attrs(cx, tcx, did),
123 visibility: Some(hir::Public),
124 stability: stability::lookup(tcx, did).clean(cx),
130 pub fn load_attrs(cx: &DocContext, tcx: &ty::ctxt,
131 did: DefId) -> Vec<clean::Attribute> {
132 let attrs = csearch::get_item_attrs(&tcx.sess.cstore, did);
133 attrs.into_iter().map(|a| a.clean(cx)).collect()
136 /// Record an external fully qualified name in the external_paths cache.
138 /// These names are used later on by HTML rendering to generate things like
139 /// source links back to the original item.
140 pub fn record_extern_fqn(cx: &DocContext, did: DefId, kind: clean::TypeKind) {
143 let fqn = csearch::get_item_path(tcx, did);
144 let fqn = fqn.into_iter().map(|i| i.to_string()).collect();
145 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, kind));
151 pub fn build_external_trait(cx: &DocContext, tcx: &ty::ctxt,
152 did: DefId) -> clean::Trait {
153 let def = tcx.lookup_trait_def(did);
154 let trait_items = tcx.trait_items(did).clean(cx);
155 let predicates = tcx.lookup_predicates(did);
156 let generics = (&def.generics, &predicates, subst::TypeSpace).clean(cx);
157 let generics = filter_non_trait_generics(did, generics);
158 let (generics, supertrait_bounds) = separate_supertrait_bounds(generics);
160 unsafety: def.unsafety,
163 bounds: supertrait_bounds,
167 fn build_external_function(cx: &DocContext, tcx: &ty::ctxt, did: DefId) -> clean::Function {
168 let t = tcx.lookup_item_type(did);
169 let (decl, style, abi) = match t.ty.sty {
170 ty::TyBareFn(_, ref f) => ((did, &f.sig).clean(cx), f.unsafety, f.abi),
171 _ => panic!("bad function"),
174 let constness = if csearch::is_const_fn(&tcx.sess.cstore, did) {
175 hir::Constness::Const
177 hir::Constness::NotConst
180 let predicates = tcx.lookup_predicates(did);
183 generics: (&t.generics, &predicates, subst::FnSpace).clean(cx),
185 constness: constness,
190 fn build_struct(cx: &DocContext, tcx: &ty::ctxt, did: DefId) -> clean::Struct {
191 use syntax::parse::token::special_idents::unnamed_field;
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 [ref f] if f.name == unnamed_field.name => doctree::Newtype,
201 [ref f, ..] if f.name == unnamed_field.name => 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: &ty::ctxt, did: DefId) -> clean::ItemEnum {
211 let t = tcx.lookup_item_type(did);
212 let predicates = tcx.lookup_predicates(did);
214 ty::TyEnum(edef, _) if !csearch::is_typedef(&tcx.sess.cstore, 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, tcx: &ty::ctxt,
231 did: DefId) -> Vec<clean::Item> {
232 tcx.populate_inherent_implementations_for_type_if_necessary(did);
233 let mut impls = Vec::new();
235 match tcx.inherent_impls.borrow().get(&did) {
238 for &did in i.iter() {
239 build_impl(cx, tcx, did, &mut impls);
244 // If this is the first time we've inlined something from this crate, then
245 // we inline *all* impls from the crate into this crate. Note that there's
246 // currently no way for us to filter this based on type, and we likely need
247 // many impls for a variety of reasons.
249 // Primarily, the impls will be used to populate the documentation for this
250 // type being inlined, but impls can also be used when generating
251 // documentation for primitives (no way to find those specifically).
252 if cx.populated_crate_impls.borrow_mut().insert(did.krate) {
253 csearch::each_top_level_item_of_crate(&tcx.sess.cstore,
256 populate_impls(cx, tcx, def, &mut impls)
259 fn populate_impls(cx: &DocContext, tcx: &ty::ctxt,
260 def: decoder::DefLike,
261 impls: &mut Vec<clean::Item>) {
263 decoder::DlImpl(did) => build_impl(cx, tcx, did, impls),
264 decoder::DlDef(def::DefMod(did)) => {
265 csearch::each_child_of_item(&tcx.sess.cstore,
268 populate_impls(cx, tcx, def, impls)
279 pub fn build_impl(cx: &DocContext,
282 ret: &mut Vec<clean::Item>) {
283 if !cx.inlined.borrow_mut().as_mut().unwrap().insert(did) {
287 let attrs = load_attrs(cx, tcx, did);
288 let associated_trait = csearch::get_impl_trait(tcx, did);
289 if let Some(ref t) = associated_trait {
290 // If this is an impl for a #[doc(hidden)] trait, be sure to not inline
291 let trait_attrs = load_attrs(cx, tcx, t.def_id);
292 if trait_attrs.iter().any(|a| is_doc_hidden(a)) {
297 // If this is a defaulted impl, then bail out early here
298 if csearch::is_default_impl(&tcx.sess.cstore, did) {
299 return ret.push(clean::Item {
300 inner: clean::DefaultImplItem(clean::DefaultImpl {
301 // FIXME: this should be decoded
302 unsafety: hir::Unsafety::Normal,
303 trait_: match associated_trait.as_ref().unwrap().clean(cx) {
304 clean::TraitBound(polyt, _) => polyt.trait_,
305 clean::RegionBound(..) => unreachable!(),
308 source: clean::Span::empty(),
311 visibility: Some(hir::Inherited),
312 stability: stability::lookup(tcx, did).clean(cx),
317 let predicates = tcx.lookup_predicates(did);
318 let trait_items = csearch::get_impl_items(&tcx.sess.cstore, did)
321 let did = did.def_id();
322 let impl_item = tcx.impl_or_trait_item(did);
324 ty::ConstTraitItem(ref assoc_const) => {
325 let did = assoc_const.def_id;
326 let type_scheme = tcx.lookup_item_type(did);
327 let default = if assoc_const.has_value {
328 Some(const_eval::lookup_const_by_id(tcx, did, None)
329 .unwrap().span.to_src(cx))
334 name: Some(assoc_const.name.clean(cx)),
335 inner: clean::AssociatedConstItem(
336 type_scheme.ty.clean(cx),
339 source: clean::Span::empty(),
342 stability: stability::lookup(tcx, did).clean(cx),
346 ty::MethodTraitItem(method) => {
347 if method.vis != hir::Public && associated_trait.is_none() {
350 let mut item = method.clean(cx);
351 item.inner = match item.inner.clone() {
352 clean::TyMethodItem(clean::TyMethod {
353 unsafety, decl, self_, generics, abi
355 let constness = if csearch::is_const_fn(&tcx.sess.cstore, did) {
356 hir::Constness::Const
358 hir::Constness::NotConst
361 clean::MethodItem(clean::Method {
363 constness: constness,
370 _ => panic!("not a tymethod"),
374 ty::TypeTraitItem(ref assoc_ty) => {
375 let did = assoc_ty.def_id;
376 let type_scheme = ty::TypeScheme {
377 ty: assoc_ty.ty.unwrap(),
378 generics: ty::Generics::empty()
380 // Not sure the choice of ParamSpace actually matters here,
381 // because an associated type won't have generics on the LHS
382 let typedef = (type_scheme, ty::GenericPredicates::empty(),
383 subst::ParamSpace::TypeSpace).clean(cx);
385 name: Some(assoc_ty.name.clean(cx)),
386 inner: clean::TypedefItem(typedef, true),
387 source: clean::Span::empty(),
390 stability: stability::lookup(tcx, did).clean(cx),
395 }).collect::<Vec<_>>();
396 let polarity = csearch::get_impl_polarity(tcx, did);
397 let ty = tcx.lookup_item_type(did);
398 let trait_ = associated_trait.clean(cx).map(|bound| {
400 clean::TraitBound(polyt, _) => polyt.trait_,
401 clean::RegionBound(..) => unreachable!(),
404 if let Some(clean::ResolvedPath { did, .. }) = trait_ {
405 if Some(did) == cx.deref_trait_did.get() {
406 super::build_deref_target_impls(cx, &trait_items, ret);
409 ret.push(clean::Item {
410 inner: clean::ImplItem(clean::Impl {
411 unsafety: hir::Unsafety::Normal, // FIXME: this should be decoded
412 derived: clean::detect_derived(&attrs),
414 for_: ty.ty.clean(cx),
415 generics: (&ty.generics, &predicates, subst::TypeSpace).clean(cx),
417 polarity: polarity.map(|p| { p.clean(cx) }),
419 source: clean::Span::empty(),
422 visibility: Some(hir::Inherited),
423 stability: stability::lookup(tcx, did).clean(cx),
427 fn is_doc_hidden(a: &clean::Attribute) -> bool {
429 clean::List(ref name, ref inner) if *name == "doc" => {
430 inner.iter().any(|a| {
432 clean::Word(ref s) => *s == "hidden",
442 fn build_module(cx: &DocContext, tcx: &ty::ctxt,
443 did: DefId) -> clean::Module {
444 let mut items = Vec::new();
445 fill_in(cx, tcx, did, &mut items);
446 return clean::Module {
451 fn fill_in(cx: &DocContext, tcx: &ty::ctxt, did: DefId,
452 items: &mut Vec<clean::Item>) {
453 // If we're reexporting a reexport it may actually reexport something in
454 // two namespaces, so the target may be listed twice. Make sure we only
455 // visit each node at most once.
456 let mut visited = HashSet::new();
457 csearch::each_child_of_item(&tcx.sess.cstore, did, |def, _, vis| {
459 decoder::DlDef(def::DefForeignMod(did)) => {
460 fill_in(cx, tcx, did, items);
462 decoder::DlDef(def) if vis == hir::Public => {
463 if !visited.insert(def) { return }
464 match try_inline_def(cx, tcx, def) {
465 Some(i) => items.extend(i),
469 decoder::DlDef(..) => {}
470 // All impls were inlined above
471 decoder::DlImpl(..) => {}
472 decoder::DlField => panic!("unimplemented field"),
478 fn build_const(cx: &DocContext, tcx: &ty::ctxt,
479 did: DefId) -> clean::Constant {
480 use rustc::middle::const_eval;
481 use rustc_front::print::pprust;
483 let expr = const_eval::lookup_const_by_id(tcx, did, None).unwrap_or_else(|| {
484 panic!("expected lookup_const_by_id to succeed for {:?}", did);
486 debug!("converting constant expr {:?} to snippet", expr);
487 let sn = pprust::expr_to_string(expr);
488 debug!("got snippet {}", sn);
491 type_: tcx.lookup_item_type(did).ty.clean(cx),
496 fn build_static(cx: &DocContext, tcx: &ty::ctxt,
498 mutable: bool) -> clean::Static {
500 type_: tcx.lookup_item_type(did).ty.clean(cx),
501 mutability: if mutable {clean::Mutable} else {clean::Immutable},
502 expr: "\n\n\n".to_string(), // trigger the "[definition]" links
506 /// A trait's generics clause actually contains all of the predicates for all of
507 /// its associated types as well. We specifically move these clauses to the
508 /// associated types instead when displaying, so when we're genering the
509 /// generics for the trait itself we need to be sure to remove them.
511 /// The inverse of this filtering logic can be found in the `Clean`
512 /// implementation for `AssociatedType`
513 fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics)
515 g.where_predicates.retain(|pred| {
517 clean::WherePredicate::BoundPredicate {
519 self_type: box clean::Generic(ref s),
520 trait_: box clean::ResolvedPath { did, .. },
523 } => *s != "Self" || did != trait_did,
530 /// Supertrait bounds for a trait are also listed in the generics coming from
531 /// the metadata for a crate, so we want to separate those out and create a new
532 /// list of explicit supertrait bounds to render nicely.
533 fn separate_supertrait_bounds(mut g: clean::Generics)
534 -> (clean::Generics, Vec<clean::TyParamBound>) {
535 let mut ty_bounds = Vec::new();
536 g.where_predicates.retain(|pred| {
538 clean::WherePredicate::BoundPredicate {
539 ty: clean::Generic(ref s),
541 } if *s == "Self" => {
542 ty_bounds.extend(bounds.iter().cloned());