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::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) -> Option<Vec<clean::Item>> {
72 let mut ret = Vec::new();
73 let did = def.def_id();
74 let inner = match def {
76 record_extern_fqn(cx, did, clean::TypeTrait);
77 clean::TraitItem(build_external_trait(cx, tcx, did))
80 record_extern_fqn(cx, did, clean::TypeFunction);
81 clean::FunctionItem(build_external_function(cx, tcx, did))
84 // If this is a struct constructor, we skip it
85 if tcx.sess.cstore.tuple_struct_definition_if_ctor(did).is_none() => {
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::TyAlias(did) => {
91 record_extern_fqn(cx, did, clean::TypeTypedef);
92 ret.extend(build_impls(cx, tcx, did));
93 build_type(cx, tcx, did)
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::Variant(..) => return Some(Vec::new()),
104 record_extern_fqn(cx, did, clean::TypeModule);
105 clean::ModuleItem(build_module(cx, tcx, did))
107 Def::Static(did, mtbl) => {
108 record_extern_fqn(cx, did, clean::TypeStatic);
109 clean::StaticItem(build_static(cx, tcx, did, mtbl))
111 Def::Const(did) | Def::AssociatedConst(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_stability(tcx, did).clean(cx),
125 deprecation: stability::lookup_deprecation(tcx, did).clean(cx),
131 pub fn load_attrs(cx: &DocContext, tcx: &ty::ctxt,
132 did: DefId) -> Vec<clean::Attribute> {
133 tcx.get_attrs(did).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 = tcx.sess.cstore.extern_item_path(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 tcx.sess.cstore.is_const_fn(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 !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, 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 for item in tcx.sess.cstore.crate_top_level_items(did.krate) {
254 populate_impls(cx, tcx, item.def, &mut impls);
257 fn populate_impls(cx: &DocContext, tcx: &ty::ctxt,
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)
275 pub fn build_impl(cx: &DocContext,
278 ret: &mut Vec<clean::Item>) {
279 if !cx.inlined.borrow_mut().as_mut().unwrap().insert(did) {
283 let attrs = load_attrs(cx, tcx, did);
284 let associated_trait = tcx.impl_trait_ref(did);
285 if let Some(ref t) = associated_trait {
286 // If this is an impl for a #[doc(hidden)] trait, be sure to not inline
287 let trait_attrs = load_attrs(cx, tcx, t.def_id);
288 if trait_attrs.iter().any(|a| is_doc_hidden(a)) {
293 // If this is a defaulted impl, then bail out early here
294 if tcx.sess.cstore.is_default_impl(did) {
295 return ret.push(clean::Item {
296 inner: clean::DefaultImplItem(clean::DefaultImpl {
297 // FIXME: this should be decoded
298 unsafety: hir::Unsafety::Normal,
299 trait_: match associated_trait.as_ref().unwrap().clean(cx) {
300 clean::TraitBound(polyt, _) => polyt.trait_,
301 clean::RegionBound(..) => unreachable!(),
304 source: clean::Span::empty(),
307 visibility: Some(hir::Inherited),
308 stability: stability::lookup_stability(tcx, did).clean(cx),
309 deprecation: stability::lookup_deprecation(tcx, did).clean(cx),
314 let predicates = tcx.lookup_predicates(did);
315 let trait_items = tcx.sess.cstore.impl_items(did)
318 let did = did.def_id();
319 let impl_item = tcx.impl_or_trait_item(did);
321 ty::ConstTraitItem(ref assoc_const) => {
322 let did = assoc_const.def_id;
323 let type_scheme = tcx.lookup_item_type(did);
324 let default = if assoc_const.has_value {
325 Some(const_eval::lookup_const_by_id(tcx, did, None, None)
326 .unwrap().span.to_src(cx))
331 name: Some(assoc_const.name.clean(cx)),
332 inner: clean::AssociatedConstItem(
333 type_scheme.ty.clean(cx),
336 source: clean::Span::empty(),
339 stability: stability::lookup_stability(tcx, did).clean(cx),
340 deprecation: stability::lookup_deprecation(tcx, did).clean(cx),
344 ty::MethodTraitItem(method) => {
345 if method.vis != hir::Public && associated_trait.is_none() {
348 let mut item = method.clean(cx);
349 item.inner = match item.inner.clone() {
350 clean::TyMethodItem(clean::TyMethod {
351 unsafety, decl, self_, generics, abi
353 let constness = if tcx.sess.cstore.is_const_fn(did) {
354 hir::Constness::Const
356 hir::Constness::NotConst
359 clean::MethodItem(clean::Method {
361 constness: constness,
368 _ => panic!("not a tymethod"),
372 ty::TypeTraitItem(ref assoc_ty) => {
373 let did = assoc_ty.def_id;
374 let type_scheme = ty::TypeScheme {
375 ty: assoc_ty.ty.unwrap(),
376 generics: ty::Generics::empty()
378 // Not sure the choice of ParamSpace actually matters here,
379 // because an associated type won't have generics on the LHS
380 let typedef = (type_scheme, ty::GenericPredicates::empty(),
381 subst::ParamSpace::TypeSpace).clean(cx);
383 name: Some(assoc_ty.name.clean(cx)),
384 inner: clean::TypedefItem(typedef, true),
385 source: clean::Span::empty(),
388 stability: stability::lookup_stability(tcx, did).clean(cx),
389 deprecation: stability::lookup_deprecation(tcx, did).clean(cx),
394 }).collect::<Vec<_>>();
395 let polarity = tcx.trait_impl_polarity(did);
396 let ty = tcx.lookup_item_type(did);
397 let trait_ = associated_trait.clean(cx).map(|bound| {
399 clean::TraitBound(polyt, _) => polyt.trait_,
400 clean::RegionBound(..) => unreachable!(),
403 if let Some(clean::ResolvedPath { did, .. }) = trait_ {
404 if Some(did) == cx.deref_trait_did.get() {
405 super::build_deref_target_impls(cx, &trait_items, ret);
408 ret.push(clean::Item {
409 inner: clean::ImplItem(clean::Impl {
410 unsafety: hir::Unsafety::Normal, // FIXME: this should be decoded
411 derived: clean::detect_derived(&attrs),
413 for_: ty.ty.clean(cx),
414 generics: (&ty.generics, &predicates, subst::TypeSpace).clean(cx),
416 polarity: polarity.map(|p| { p.clean(cx) }),
418 source: clean::Span::empty(),
421 visibility: Some(hir::Inherited),
422 stability: stability::lookup_stability(tcx, did).clean(cx),
423 deprecation: stability::lookup_deprecation(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 for item in tcx.sess.cstore.item_children(did) {
459 cstore::DlDef(Def::ForeignMod(did)) => {
460 fill_in(cx, tcx, did, items);
462 cstore::DlDef(def) if item.vis == hir::Public => {
463 if !visited.insert(def) { continue }
464 match try_inline_def(cx, tcx, def) {
465 Some(i) => items.extend(i),
469 cstore::DlDef(..) => {}
470 // All impls were inlined above
471 cstore::DlImpl(..) => {}
472 cstore::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, 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());