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_stability(tcx, did).clean(cx),
124 deprecation: stability::lookup_deprecation(tcx, did).clean(cx),
130 pub fn load_attrs(cx: &DocContext, tcx: &ty::ctxt,
131 did: DefId) -> Vec<clean::Attribute> {
132 tcx.get_attrs(did).iter().map(|a| a.clean(cx)).collect()
135 /// Record an external fully qualified name in the external_paths cache.
137 /// These names are used later on by HTML rendering to generate things like
138 /// source links back to the original item.
139 pub fn record_extern_fqn(cx: &DocContext, did: DefId, kind: clean::TypeKind) {
142 let fqn = tcx.sess.cstore.extern_item_path(did);
143 let fqn = fqn.into_iter().map(|i| i.to_string()).collect();
144 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, kind));
150 pub fn build_external_trait(cx: &DocContext, tcx: &ty::ctxt,
151 did: DefId) -> clean::Trait {
152 let def = tcx.lookup_trait_def(did);
153 let trait_items = tcx.trait_items(did).clean(cx);
154 let predicates = tcx.lookup_predicates(did);
155 let generics = (&def.generics, &predicates, subst::TypeSpace).clean(cx);
156 let generics = filter_non_trait_generics(did, generics);
157 let (generics, supertrait_bounds) = separate_supertrait_bounds(generics);
159 unsafety: def.unsafety,
162 bounds: supertrait_bounds,
166 fn build_external_function(cx: &DocContext, tcx: &ty::ctxt, did: DefId) -> clean::Function {
167 let t = tcx.lookup_item_type(did);
168 let (decl, style, abi) = match t.ty.sty {
169 ty::TyBareFn(_, ref f) => ((did, &f.sig).clean(cx), f.unsafety, f.abi),
170 _ => panic!("bad function"),
173 let constness = if tcx.sess.cstore.is_const_fn(did) {
174 hir::Constness::Const
176 hir::Constness::NotConst
179 let predicates = tcx.lookup_predicates(did);
182 generics: (&t.generics, &predicates, subst::FnSpace).clean(cx),
184 constness: constness,
189 fn build_struct(cx: &DocContext, tcx: &ty::ctxt, did: DefId) -> clean::Struct {
190 use syntax::parse::token::special_idents::unnamed_field;
192 let t = tcx.lookup_item_type(did);
193 let predicates = tcx.lookup_predicates(did);
194 let variant = tcx.lookup_adt_def(did).struct_variant();
197 struct_type: match &*variant.fields {
199 [ref f] if f.name == unnamed_field.name => doctree::Newtype,
200 [ref f, ..] if f.name == unnamed_field.name => doctree::Tuple,
203 generics: (&t.generics, &predicates, subst::TypeSpace).clean(cx),
204 fields: variant.fields.clean(cx),
205 fields_stripped: false,
209 fn build_type(cx: &DocContext, tcx: &ty::ctxt, did: DefId) -> clean::ItemEnum {
210 let t = tcx.lookup_item_type(did);
211 let predicates = tcx.lookup_predicates(did);
213 ty::TyEnum(edef, _) if !tcx.sess.cstore.is_typedef(did) => {
214 return clean::EnumItem(clean::Enum {
215 generics: (&t.generics, &predicates, subst::TypeSpace).clean(cx),
216 variants_stripped: false,
217 variants: edef.variants.clean(cx),
223 clean::TypedefItem(clean::Typedef {
224 type_: t.ty.clean(cx),
225 generics: (&t.generics, &predicates, subst::TypeSpace).clean(cx),
229 pub fn build_impls(cx: &DocContext, tcx: &ty::ctxt,
230 did: DefId) -> Vec<clean::Item> {
231 tcx.populate_inherent_implementations_for_type_if_necessary(did);
232 let mut impls = Vec::new();
234 match tcx.inherent_impls.borrow().get(&did) {
237 for &did in i.iter() {
238 build_impl(cx, tcx, did, &mut impls);
243 // If this is the first time we've inlined something from this crate, then
244 // we inline *all* impls from the crate into this crate. Note that there's
245 // currently no way for us to filter this based on type, and we likely need
246 // many impls for a variety of reasons.
248 // Primarily, the impls will be used to populate the documentation for this
249 // type being inlined, but impls can also be used when generating
250 // documentation for primitives (no way to find those specifically).
251 if cx.populated_crate_impls.borrow_mut().insert(did.krate) {
252 for item in tcx.sess.cstore.crate_top_level_items(did.krate) {
253 populate_impls(cx, tcx, item.def, &mut impls);
256 fn populate_impls(cx: &DocContext, tcx: &ty::ctxt,
257 def: cstore::DefLike,
258 impls: &mut Vec<clean::Item>) {
260 cstore::DlImpl(did) => build_impl(cx, tcx, did, impls),
261 cstore::DlDef(def::DefMod(did)) => {
262 for item in tcx.sess.cstore.item_children(did) {
263 populate_impls(cx, tcx, item.def, impls)
274 pub fn build_impl(cx: &DocContext,
277 ret: &mut Vec<clean::Item>) {
278 if !cx.inlined.borrow_mut().as_mut().unwrap().insert(did) {
282 let attrs = load_attrs(cx, tcx, did);
283 let associated_trait = tcx.impl_trait_ref(did);
284 if let Some(ref t) = associated_trait {
285 // If this is an impl for a #[doc(hidden)] trait, be sure to not inline
286 let trait_attrs = load_attrs(cx, tcx, t.def_id);
287 if trait_attrs.iter().any(|a| is_doc_hidden(a)) {
292 // If this is a defaulted impl, then bail out early here
293 if tcx.sess.cstore.is_default_impl(did) {
294 return ret.push(clean::Item {
295 inner: clean::DefaultImplItem(clean::DefaultImpl {
296 // FIXME: this should be decoded
297 unsafety: hir::Unsafety::Normal,
298 trait_: match associated_trait.as_ref().unwrap().clean(cx) {
299 clean::TraitBound(polyt, _) => polyt.trait_,
300 clean::RegionBound(..) => unreachable!(),
303 source: clean::Span::empty(),
306 visibility: Some(hir::Inherited),
307 stability: stability::lookup_stability(tcx, did).clean(cx),
308 deprecation: stability::lookup_deprecation(tcx, did).clean(cx),
313 let predicates = tcx.lookup_predicates(did);
314 let trait_items = tcx.sess.cstore.impl_items(did)
317 let did = did.def_id();
318 let impl_item = tcx.impl_or_trait_item(did);
320 ty::ConstTraitItem(ref assoc_const) => {
321 let did = assoc_const.def_id;
322 let type_scheme = tcx.lookup_item_type(did);
323 let default = if assoc_const.has_value {
324 Some(const_eval::lookup_const_by_id(tcx, did, None, None)
325 .unwrap().span.to_src(cx))
330 name: Some(assoc_const.name.clean(cx)),
331 inner: clean::AssociatedConstItem(
332 type_scheme.ty.clean(cx),
335 source: clean::Span::empty(),
338 stability: stability::lookup_stability(tcx, did).clean(cx),
339 deprecation: stability::lookup_deprecation(tcx, did).clean(cx),
343 ty::MethodTraitItem(method) => {
344 if method.vis != hir::Public && associated_trait.is_none() {
347 let mut item = method.clean(cx);
348 item.inner = match item.inner.clone() {
349 clean::TyMethodItem(clean::TyMethod {
350 unsafety, decl, self_, generics, abi
352 let constness = if tcx.sess.cstore.is_const_fn(did) {
353 hir::Constness::Const
355 hir::Constness::NotConst
358 clean::MethodItem(clean::Method {
360 constness: constness,
367 _ => panic!("not a tymethod"),
371 ty::TypeTraitItem(ref assoc_ty) => {
372 let did = assoc_ty.def_id;
373 let type_scheme = ty::TypeScheme {
374 ty: assoc_ty.ty.unwrap(),
375 generics: ty::Generics::empty()
377 // Not sure the choice of ParamSpace actually matters here,
378 // because an associated type won't have generics on the LHS
379 let typedef = (type_scheme, ty::GenericPredicates::empty(),
380 subst::ParamSpace::TypeSpace).clean(cx);
382 name: Some(assoc_ty.name.clean(cx)),
383 inner: clean::TypedefItem(typedef, true),
384 source: clean::Span::empty(),
387 stability: stability::lookup_stability(tcx, did).clean(cx),
388 deprecation: stability::lookup_deprecation(tcx, did).clean(cx),
393 }).collect::<Vec<_>>();
394 let polarity = tcx.trait_impl_polarity(did);
395 let ty = tcx.lookup_item_type(did);
396 let trait_ = associated_trait.clean(cx).map(|bound| {
398 clean::TraitBound(polyt, _) => polyt.trait_,
399 clean::RegionBound(..) => unreachable!(),
402 if let Some(clean::ResolvedPath { did, .. }) = trait_ {
403 if Some(did) == cx.deref_trait_did.get() {
404 super::build_deref_target_impls(cx, &trait_items, ret);
407 ret.push(clean::Item {
408 inner: clean::ImplItem(clean::Impl {
409 unsafety: hir::Unsafety::Normal, // FIXME: this should be decoded
410 derived: clean::detect_derived(&attrs),
412 for_: ty.ty.clean(cx),
413 generics: (&ty.generics, &predicates, subst::TypeSpace).clean(cx),
415 polarity: polarity.map(|p| { p.clean(cx) }),
417 source: clean::Span::empty(),
420 visibility: Some(hir::Inherited),
421 stability: stability::lookup_stability(tcx, did).clean(cx),
422 deprecation: stability::lookup_deprecation(tcx, did).clean(cx),
426 fn is_doc_hidden(a: &clean::Attribute) -> bool {
428 clean::List(ref name, ref inner) if *name == "doc" => {
429 inner.iter().any(|a| {
431 clean::Word(ref s) => *s == "hidden",
441 fn build_module(cx: &DocContext, tcx: &ty::ctxt,
442 did: DefId) -> clean::Module {
443 let mut items = Vec::new();
444 fill_in(cx, tcx, did, &mut items);
445 return clean::Module {
450 fn fill_in(cx: &DocContext, tcx: &ty::ctxt, did: DefId,
451 items: &mut Vec<clean::Item>) {
452 // If we're reexporting a reexport it may actually reexport something in
453 // two namespaces, so the target may be listed twice. Make sure we only
454 // visit each node at most once.
455 let mut visited = HashSet::new();
456 for item in tcx.sess.cstore.item_children(did) {
458 cstore::DlDef(def::DefForeignMod(did)) => {
459 fill_in(cx, tcx, did, items);
461 cstore::DlDef(def) if item.vis == hir::Public => {
462 if !visited.insert(def) { continue }
463 match try_inline_def(cx, tcx, def) {
464 Some(i) => items.extend(i),
468 cstore::DlDef(..) => {}
469 // All impls were inlined above
470 cstore::DlImpl(..) => {}
471 cstore::DlField => panic!("unimplemented field"),
477 fn build_const(cx: &DocContext, tcx: &ty::ctxt,
478 did: DefId) -> clean::Constant {
479 use rustc::middle::const_eval;
480 use rustc_front::print::pprust;
482 let expr = const_eval::lookup_const_by_id(tcx, did, None, None).unwrap_or_else(|| {
483 panic!("expected lookup_const_by_id to succeed for {:?}", did);
485 debug!("converting constant expr {:?} to snippet", expr);
486 let sn = pprust::expr_to_string(expr);
487 debug!("got snippet {}", sn);
490 type_: tcx.lookup_item_type(did).ty.clean(cx),
495 fn build_static(cx: &DocContext, tcx: &ty::ctxt,
497 mutable: bool) -> clean::Static {
499 type_: tcx.lookup_item_type(did).ty.clean(cx),
500 mutability: if mutable {clean::Mutable} else {clean::Immutable},
501 expr: "\n\n\n".to_string(), // trigger the "[definition]" links
505 /// A trait's generics clause actually contains all of the predicates for all of
506 /// its associated types as well. We specifically move these clauses to the
507 /// associated types instead when displaying, so when we're genering the
508 /// generics for the trait itself we need to be sure to remove them.
510 /// The inverse of this filtering logic can be found in the `Clean`
511 /// implementation for `AssociatedType`
512 fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics)
514 g.where_predicates.retain(|pred| {
516 clean::WherePredicate::BoundPredicate {
518 self_type: box clean::Generic(ref s),
519 trait_: box clean::ResolvedPath { did, .. },
522 } => *s != "Self" || did != trait_did,
529 /// Supertrait bounds for a trait are also listed in the generics coming from
530 /// the metadata for a crate, so we want to separate those out and create a new
531 /// list of explicit supertrait bounds to render nicely.
532 fn separate_supertrait_bounds(mut g: clean::Generics)
533 -> (clean::Generics, Vec<clean::TyParamBound>) {
534 let mut ty_bounds = Vec::new();
535 g.where_predicates.retain(|pred| {
537 clean::WherePredicate::BoundPredicate {
538 ty: clean::Generic(ref s),
540 } if *s == "Self" => {
541 ty_bounds.extend(bounds.iter().cloned());