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::middle::cstore::{self, CrateStore};
20 use rustc::middle::def;
21 use rustc::middle::def_id::DefId;
22 use rustc::middle::ty;
23 use rustc::middle::subst;
24 use rustc::middle::stability;
25 use rustc::middle::const_eval;
31 use super::{Clean, ToSource};
33 /// Attempt to inline the definition of a local node id into this AST.
35 /// This function will fetch the definition of the id specified, and if it is
36 /// from another crate it will attempt to inline the documentation from the
37 /// other crate into this crate.
39 /// This is primarily used for `pub use` statements which are, in general,
40 /// implementation details. Inlining the documentation should help provide a
41 /// better experience when reading the documentation in this use case.
43 /// The returned value is `None` if the `id` could not be inlined, and `Some`
44 /// of a vector of items if it was successfully expanded.
45 pub fn try_inline(cx: &DocContext, id: ast::NodeId, into: Option<ast::Name>)
46 -> Option<Vec<clean::Item>> {
47 let tcx = match cx.tcx_opt() {
51 let def = match tcx.def_map.borrow().get(&id) {
52 Some(d) => d.full_def(),
55 let did = def.def_id();
56 if did.is_local() { return None }
57 try_inline_def(cx, tcx, def).map(|vec| {
58 vec.into_iter().map(|mut item| {
60 Some(into) if item.name.is_some() => {
61 item.name = Some(into.clean(cx));
70 fn try_inline_def(cx: &DocContext, tcx: &ty::ctxt,
71 def: def::Def) -> Option<Vec<clean::Item>> {
72 let mut ret = Vec::new();
73 let did = def.def_id();
74 let inner = match def {
75 def::DefTrait(did) => {
76 record_extern_fqn(cx, did, clean::TypeTrait);
77 clean::TraitItem(build_external_trait(cx, tcx, did))
79 def::DefFn(did, false) => {
80 // If this function is a tuple struct constructor, we just skip it
81 record_extern_fqn(cx, did, clean::TypeFunction);
82 clean::FunctionItem(build_external_function(cx, tcx, did))
84 def::DefStruct(did) => {
85 record_extern_fqn(cx, did, clean::TypeStruct);
86 ret.extend(build_impls(cx, tcx, did));
87 clean::StructItem(build_struct(cx, tcx, did))
89 def::DefTy(did, false) => {
90 record_extern_fqn(cx, did, clean::TypeTypedef);
91 ret.extend(build_impls(cx, tcx, did));
92 build_type(cx, tcx, did)
94 def::DefTy(did, true) => {
95 record_extern_fqn(cx, did, clean::TypeEnum);
96 ret.extend(build_impls(cx, tcx, did));
97 build_type(cx, tcx, did)
99 // Assume that the enum type is reexported next to the variant, and
100 // variants don't show up in documentation specially.
101 def::DefVariant(..) => return Some(Vec::new()),
102 def::DefMod(did) => {
103 record_extern_fqn(cx, did, clean::TypeModule);
104 clean::ModuleItem(build_module(cx, tcx, did))
106 def::DefStatic(did, mtbl) => {
107 record_extern_fqn(cx, did, clean::TypeStatic);
108 clean::StaticItem(build_static(cx, tcx, did, mtbl))
110 def::DefConst(did) | def::DefAssociatedConst(did) => {
111 record_extern_fqn(cx, did, clean::TypeConst);
112 clean::ConstantItem(build_const(cx, tcx, did))
116 cx.inlined.borrow_mut().as_mut().unwrap().insert(did);
117 ret.push(clean::Item {
118 source: clean::Span::empty(),
119 name: Some(tcx.item_name(did).to_string()),
120 attrs: load_attrs(cx, tcx, did),
122 visibility: Some(hir::Public),
123 stability: stability::lookup(tcx, did).clean(cx),
129 pub fn load_attrs(cx: &DocContext, tcx: &ty::ctxt,
130 did: DefId) -> Vec<clean::Attribute> {
131 tcx.get_attrs(did).iter().map(|a| a.clean(cx)).collect()
134 /// Record an external fully qualified name in the external_paths cache.
136 /// These names are used later on by HTML rendering to generate things like
137 /// source links back to the original item.
138 pub fn record_extern_fqn(cx: &DocContext, did: DefId, kind: clean::TypeKind) {
141 let fqn = tcx.sess.cstore.item_path(did);
142 let fqn = fqn.into_iter().map(|i| i.to_string()).collect();
143 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, kind));
149 pub fn build_external_trait(cx: &DocContext, tcx: &ty::ctxt,
150 did: DefId) -> clean::Trait {
151 let def = tcx.lookup_trait_def(did);
152 let trait_items = tcx.trait_items(did).clean(cx);
153 let predicates = tcx.lookup_predicates(did);
154 let generics = (&def.generics, &predicates, subst::TypeSpace).clean(cx);
155 let generics = filter_non_trait_generics(did, generics);
156 let (generics, supertrait_bounds) = separate_supertrait_bounds(generics);
158 unsafety: def.unsafety,
161 bounds: supertrait_bounds,
165 fn build_external_function(cx: &DocContext, tcx: &ty::ctxt, did: DefId) -> clean::Function {
166 let t = tcx.lookup_item_type(did);
167 let (decl, style, abi) = match t.ty.sty {
168 ty::TyBareFn(_, ref f) => ((did, &f.sig).clean(cx), f.unsafety, f.abi),
169 _ => panic!("bad function"),
172 let constness = if tcx.sess.cstore.is_const_fn(did) {
173 hir::Constness::Const
175 hir::Constness::NotConst
178 let predicates = tcx.lookup_predicates(did);
181 generics: (&t.generics, &predicates, subst::FnSpace).clean(cx),
183 constness: constness,
188 fn build_struct(cx: &DocContext, tcx: &ty::ctxt, did: DefId) -> clean::Struct {
189 use syntax::parse::token::special_idents::unnamed_field;
191 let t = tcx.lookup_item_type(did);
192 let predicates = tcx.lookup_predicates(did);
193 let variant = tcx.lookup_adt_def(did).struct_variant();
196 struct_type: match &*variant.fields {
198 [ref f] if f.name == unnamed_field.name => doctree::Newtype,
199 [ref f, ..] if f.name == unnamed_field.name => doctree::Tuple,
202 generics: (&t.generics, &predicates, subst::TypeSpace).clean(cx),
203 fields: variant.fields.clean(cx),
204 fields_stripped: false,
208 fn build_type(cx: &DocContext, tcx: &ty::ctxt, did: DefId) -> clean::ItemEnum {
209 let t = tcx.lookup_item_type(did);
210 let predicates = tcx.lookup_predicates(did);
212 ty::TyEnum(edef, _) if !tcx.sess.cstore.is_typedef(did) => {
213 return clean::EnumItem(clean::Enum {
214 generics: (&t.generics, &predicates, subst::TypeSpace).clean(cx),
215 variants_stripped: false,
216 variants: edef.variants.clean(cx),
222 clean::TypedefItem(clean::Typedef {
223 type_: t.ty.clean(cx),
224 generics: (&t.generics, &predicates, subst::TypeSpace).clean(cx),
228 pub fn build_impls(cx: &DocContext, tcx: &ty::ctxt,
229 did: DefId) -> Vec<clean::Item> {
230 tcx.populate_inherent_implementations_for_type_if_necessary(did);
231 let mut impls = Vec::new();
233 match tcx.inherent_impls.borrow().get(&did) {
236 for &did in i.iter() {
237 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.populated_crate_impls.borrow_mut().insert(did.krate) {
251 for item in tcx.sess.cstore.crate_top_level_items(did.krate) {
252 populate_impls(cx, tcx, item.def, &mut impls);
255 fn populate_impls(cx: &DocContext, tcx: &ty::ctxt,
256 def: cstore::DefLike,
257 impls: &mut Vec<clean::Item>) {
259 cstore::DlImpl(did) => build_impl(cx, tcx, did, impls),
260 cstore::DlDef(def::DefMod(did)) => {
261 for item in tcx.sess.cstore.item_children(did) {
262 populate_impls(cx, tcx, item.def, impls)
273 pub fn build_impl(cx: &DocContext,
276 ret: &mut Vec<clean::Item>) {
277 if !cx.inlined.borrow_mut().as_mut().unwrap().insert(did) {
281 let attrs = load_attrs(cx, tcx, did);
282 let associated_trait = tcx.impl_trait_ref(did);
283 if let Some(ref t) = associated_trait {
284 // If this is an impl for a #[doc(hidden)] trait, be sure to not inline
285 let trait_attrs = load_attrs(cx, tcx, t.def_id);
286 if trait_attrs.iter().any(|a| is_doc_hidden(a)) {
291 // If this is a defaulted impl, then bail out early here
292 if tcx.sess.cstore.is_default_impl(did) {
293 return ret.push(clean::Item {
294 inner: clean::DefaultImplItem(clean::DefaultImpl {
295 // FIXME: this should be decoded
296 unsafety: hir::Unsafety::Normal,
297 trait_: match associated_trait.as_ref().unwrap().clean(cx) {
298 clean::TraitBound(polyt, _) => polyt.trait_,
299 clean::RegionBound(..) => unreachable!(),
302 source: clean::Span::empty(),
305 visibility: Some(hir::Inherited),
306 stability: stability::lookup(tcx, did).clean(cx),
311 let predicates = tcx.lookup_predicates(did);
312 let trait_items = tcx.sess.cstore.impl_items(did)
315 let did = did.def_id();
316 let impl_item = tcx.impl_or_trait_item(did);
318 ty::ConstTraitItem(ref assoc_const) => {
319 let did = assoc_const.def_id;
320 let type_scheme = tcx.lookup_item_type(did);
321 let default = if assoc_const.has_value {
322 Some(const_eval::lookup_const_by_id(tcx, did, None)
323 .unwrap().span.to_src(cx))
328 name: Some(assoc_const.name.clean(cx)),
329 inner: clean::AssociatedConstItem(
330 type_scheme.ty.clean(cx),
333 source: clean::Span::empty(),
336 stability: stability::lookup(tcx, did).clean(cx),
340 ty::MethodTraitItem(method) => {
341 if method.vis != hir::Public && associated_trait.is_none() {
344 let mut item = method.clean(cx);
345 item.inner = match item.inner.clone() {
346 clean::TyMethodItem(clean::TyMethod {
347 unsafety, decl, self_, generics, abi
349 let constness = if tcx.sess.cstore.is_const_fn(did) {
350 hir::Constness::Const
352 hir::Constness::NotConst
355 clean::MethodItem(clean::Method {
357 constness: constness,
364 _ => panic!("not a tymethod"),
368 ty::TypeTraitItem(ref assoc_ty) => {
369 let did = assoc_ty.def_id;
370 let type_scheme = ty::TypeScheme {
371 ty: assoc_ty.ty.unwrap(),
372 generics: ty::Generics::empty()
374 // Not sure the choice of ParamSpace actually matters here,
375 // because an associated type won't have generics on the LHS
376 let typedef = (type_scheme, ty::GenericPredicates::empty(),
377 subst::ParamSpace::TypeSpace).clean(cx);
379 name: Some(assoc_ty.name.clean(cx)),
380 inner: clean::TypedefItem(typedef, true),
381 source: clean::Span::empty(),
384 stability: stability::lookup(tcx, did).clean(cx),
389 }).collect::<Vec<_>>();
390 let polarity = tcx.trait_impl_polarity(did);
391 let ty = tcx.lookup_item_type(did);
392 let trait_ = associated_trait.clean(cx).map(|bound| {
394 clean::TraitBound(polyt, _) => polyt.trait_,
395 clean::RegionBound(..) => unreachable!(),
398 if let Some(clean::ResolvedPath { did, .. }) = trait_ {
399 if Some(did) == cx.deref_trait_did.get() {
400 super::build_deref_target_impls(cx, &trait_items, ret);
403 ret.push(clean::Item {
404 inner: clean::ImplItem(clean::Impl {
405 unsafety: hir::Unsafety::Normal, // FIXME: this should be decoded
406 derived: clean::detect_derived(&attrs),
408 for_: ty.ty.clean(cx),
409 generics: (&ty.generics, &predicates, subst::TypeSpace).clean(cx),
411 polarity: polarity.map(|p| { p.clean(cx) }),
413 source: clean::Span::empty(),
416 visibility: Some(hir::Inherited),
417 stability: stability::lookup(tcx, did).clean(cx),
421 fn is_doc_hidden(a: &clean::Attribute) -> bool {
423 clean::List(ref name, ref inner) if *name == "doc" => {
424 inner.iter().any(|a| {
426 clean::Word(ref s) => *s == "hidden",
436 fn build_module(cx: &DocContext, tcx: &ty::ctxt,
437 did: DefId) -> clean::Module {
438 let mut items = Vec::new();
439 fill_in(cx, tcx, did, &mut items);
440 return clean::Module {
445 fn fill_in(cx: &DocContext, tcx: &ty::ctxt, did: DefId,
446 items: &mut Vec<clean::Item>) {
447 // If we're reexporting a reexport it may actually reexport something in
448 // two namespaces, so the target may be listed twice. Make sure we only
449 // visit each node at most once.
450 let mut visited = HashSet::new();
451 for item in tcx.sess.cstore.item_children(did) {
453 cstore::DlDef(def::DefForeignMod(did)) => {
454 fill_in(cx, tcx, did, items);
456 cstore::DlDef(def) if item.vis == hir::Public => {
457 if !visited.insert(def) { return }
458 match try_inline_def(cx, tcx, def) {
459 Some(i) => items.extend(i),
463 cstore::DlDef(..) => {}
464 // All impls were inlined above
465 cstore::DlImpl(..) => {}
466 cstore::DlField => panic!("unimplemented field"),
472 fn build_const(cx: &DocContext, tcx: &ty::ctxt,
473 did: DefId) -> clean::Constant {
474 use rustc::middle::const_eval;
475 use rustc_front::print::pprust;
477 let expr = const_eval::lookup_const_by_id(tcx, did, None).unwrap_or_else(|| {
478 panic!("expected lookup_const_by_id to succeed for {:?}", did);
480 debug!("converting constant expr {:?} to snippet", expr);
481 let sn = pprust::expr_to_string(expr);
482 debug!("got snippet {}", sn);
485 type_: tcx.lookup_item_type(did).ty.clean(cx),
490 fn build_static(cx: &DocContext, tcx: &ty::ctxt,
492 mutable: bool) -> clean::Static {
494 type_: tcx.lookup_item_type(did).ty.clean(cx),
495 mutability: if mutable {clean::Mutable} else {clean::Immutable},
496 expr: "\n\n\n".to_string(), // trigger the "[definition]" links
500 /// A trait's generics clause actually contains all of the predicates for all of
501 /// its associated types as well. We specifically move these clauses to the
502 /// associated types instead when displaying, so when we're genering the
503 /// generics for the trait itself we need to be sure to remove them.
505 /// The inverse of this filtering logic can be found in the `Clean`
506 /// implementation for `AssociatedType`
507 fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics)
509 g.where_predicates.retain(|pred| {
511 clean::WherePredicate::BoundPredicate {
513 self_type: box clean::Generic(ref s),
514 trait_: box clean::ResolvedPath { did, .. },
517 } => *s != "Self" || did != trait_did,
524 /// Supertrait bounds for a trait are also listed in the generics coming from
525 /// the metadata for a crate, so we want to separate those out and create a new
526 /// list of explicit supertrait bounds to render nicely.
527 fn separate_supertrait_bounds(mut g: clean::Generics)
528 -> (clean::Generics, Vec<clean::TyParamBound>) {
529 let mut ty_bounds = Vec::new();
530 g.where_predicates.retain(|pred| {
532 clean::WherePredicate::BoundPredicate {
533 ty: clean::Generic(ref s),
535 } if *s == "Self" => {
536 ty_bounds.extend(bounds.iter().cloned());