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.
15 use syntax::attr::AttrMetaMethods;
17 use rustc::metadata::csearch;
18 use rustc::metadata::decoder;
19 use rustc::middle::def;
20 use rustc::middle::ty;
21 use rustc::middle::subst;
22 use rustc::middle::stability;
30 /// Attempt to inline the definition of a local node id into this AST.
32 /// This function will fetch the definition of the id specified, and if it is
33 /// from another crate it will attempt to inline the documentation from the
34 /// other crate into this crate.
36 /// This is primarily used for `pub use` statements which are, in general,
37 /// implementation details. Inlining the documentation should help provide a
38 /// better experience when reading the documentation in this use case.
40 /// The returned value is `None` if the `id` could not be inlined, and `Some`
41 /// of a vector of items if it was successfully expanded.
42 pub fn try_inline(cx: &DocContext, id: ast::NodeId, into: Option<ast::Ident>)
43 -> Option<Vec<clean::Item>> {
44 let tcx = match cx.tcx_opt() {
48 let def = match tcx.def_map.borrow().get(&id) {
49 Some(d) => d.full_def(),
52 let did = def.def_id();
53 if ast_util::is_local(did) { return None }
54 try_inline_def(cx, tcx, def).map(|vec| {
55 vec.into_iter().map(|mut item| {
57 Some(into) if item.name.is_some() => {
58 item.name = Some(into.clean(cx));
67 fn try_inline_def(cx: &DocContext, tcx: &ty::ctxt,
68 def: def::Def) -> Option<Vec<clean::Item>> {
69 let mut ret = Vec::new();
70 let did = def.def_id();
71 let inner = match def {
72 def::DefTrait(did) => {
73 record_extern_fqn(cx, did, clean::TypeTrait);
74 clean::TraitItem(build_external_trait(cx, tcx, did))
76 def::DefFn(did, false) => {
77 // If this function is a tuple struct constructor, we just skip it
78 record_extern_fqn(cx, did, clean::TypeFunction);
79 clean::FunctionItem(build_external_function(cx, tcx, did))
81 def::DefStruct(did) => {
82 record_extern_fqn(cx, did, clean::TypeStruct);
83 ret.extend(build_impls(cx, tcx, did).into_iter());
84 clean::StructItem(build_struct(cx, tcx, did))
86 def::DefTy(did, false) => {
87 record_extern_fqn(cx, did, clean::TypeTypedef);
88 ret.extend(build_impls(cx, tcx, did).into_iter());
89 build_type(cx, tcx, did)
91 def::DefTy(did, true) => {
92 record_extern_fqn(cx, did, clean::TypeEnum);
93 ret.extend(build_impls(cx, tcx, did).into_iter());
94 build_type(cx, tcx, did)
96 // Assume that the enum type is reexported next to the variant, and
97 // variants don't show up in documentation specially.
98 def::DefVariant(..) => return Some(Vec::new()),
100 record_extern_fqn(cx, did, clean::TypeModule);
101 clean::ModuleItem(build_module(cx, tcx, did))
103 def::DefStatic(did, mtbl) => {
104 record_extern_fqn(cx, did, clean::TypeStatic);
105 clean::StaticItem(build_static(cx, tcx, did, mtbl))
107 def::DefConst(did) => {
108 record_extern_fqn(cx, did, clean::TypeConst);
109 clean::ConstantItem(build_const(cx, tcx, did))
113 let fqn = csearch::get_item_path(tcx, did);
114 cx.inlined.borrow_mut().as_mut().unwrap().insert(did);
115 ret.push(clean::Item {
116 source: clean::Span::empty(),
117 name: Some(fqn.last().unwrap().to_string()),
118 attrs: load_attrs(cx, tcx, did),
120 visibility: Some(ast::Public),
121 stability: stability::lookup(tcx, did).clean(cx),
127 pub fn load_attrs(cx: &DocContext, tcx: &ty::ctxt,
128 did: ast::DefId) -> Vec<clean::Attribute> {
129 let attrs = csearch::get_item_attrs(&tcx.sess.cstore, did);
130 attrs.into_iter().map(|a| a.clean(cx)).collect()
133 /// Record an external fully qualified name in the external_paths cache.
135 /// These names are used later on by HTML rendering to generate things like
136 /// source links back to the original item.
137 pub fn record_extern_fqn(cx: &DocContext, did: ast::DefId, kind: clean::TypeKind) {
140 let fqn = csearch::get_item_path(tcx, did);
141 let fqn = fqn.into_iter().map(|i| i.to_string()).collect();
142 cx.external_paths.borrow_mut().as_mut().unwrap().insert(did, (fqn, kind));
148 pub fn build_external_trait(cx: &DocContext, tcx: &ty::ctxt,
149 did: ast::DefId) -> clean::Trait {
150 use clean::TraitMethod;
152 let def = ty::lookup_trait_def(tcx, did);
153 let trait_items = ty::trait_items(tcx, did).clean(cx);
154 let provided = ty::provided_trait_methods(tcx, did);
155 let items = trait_items.into_iter().map(|trait_item| {
156 match trait_item.inner {
157 clean::TyMethodItem(_) => {
158 if provided.iter().any(|a| a.def_id == trait_item.def_id) {
159 TraitMethod::ProvidedMethod(trait_item)
161 TraitMethod::RequiredMethod(trait_item)
164 clean::AssociatedTypeItem(_) => TraitMethod::TypeTraitItem(trait_item),
168 let trait_def = ty::lookup_trait_def(tcx, did);
169 let predicates = ty::lookup_predicates(tcx, did);
170 let bounds = trait_def.bounds.clean(cx);
172 unsafety: def.unsafety,
173 generics: (&def.generics, &predicates, subst::TypeSpace).clean(cx),
174 items: items.collect(),
179 fn build_external_function(cx: &DocContext, tcx: &ty::ctxt, did: ast::DefId) -> clean::Function {
180 let t = ty::lookup_item_type(tcx, did);
181 let (decl, style) = match t.ty.sty {
182 ty::ty_bare_fn(_, ref f) => ((did, &f.sig).clean(cx), f.unsafety),
183 _ => panic!("bad function"),
185 let predicates = ty::lookup_predicates(tcx, did);
188 generics: (&t.generics, &predicates, subst::FnSpace).clean(cx),
193 fn build_struct(cx: &DocContext, tcx: &ty::ctxt, did: ast::DefId) -> clean::Struct {
194 use syntax::parse::token::special_idents::unnamed_field;
196 let t = ty::lookup_item_type(tcx, did);
197 let predicates = ty::lookup_predicates(tcx, did);
198 let fields = ty::lookup_struct_fields(tcx, did);
201 struct_type: match &*fields {
203 [ref f] if f.name == unnamed_field.name => doctree::Newtype,
204 [ref f, ..] if f.name == unnamed_field.name => doctree::Tuple,
207 generics: (&t.generics, &predicates, subst::TypeSpace).clean(cx),
208 fields: fields.clean(cx),
209 fields_stripped: false,
213 fn build_type(cx: &DocContext, tcx: &ty::ctxt, did: ast::DefId) -> clean::ItemEnum {
214 let t = ty::lookup_item_type(tcx, did);
215 let predicates = ty::lookup_predicates(tcx, did);
217 ty::ty_enum(edid, _) if !csearch::is_typedef(&tcx.sess.cstore, did) => {
218 return clean::EnumItem(clean::Enum {
219 generics: (&t.generics, &predicates, subst::TypeSpace).clean(cx),
220 variants_stripped: false,
221 variants: ty::enum_variants(tcx, edid).clean(cx),
227 clean::TypedefItem(clean::Typedef {
228 type_: t.ty.clean(cx),
229 generics: (&t.generics, &predicates, subst::TypeSpace).clean(cx),
233 fn build_impls(cx: &DocContext, tcx: &ty::ctxt,
234 did: ast::DefId) -> Vec<clean::Item> {
235 ty::populate_implementations_for_type_if_necessary(tcx, did);
236 let mut impls = Vec::new();
238 match tcx.inherent_impls.borrow().get(&did) {
241 impls.extend(i.iter().map(|&did| { build_impl(cx, tcx, did) }));
245 // If this is the first time we've inlined something from this crate, then
246 // we inline *all* impls from the crate into this crate. Note that there's
247 // currently no way for us to filter this based on type, and we likely need
248 // many impls for a variety of reasons.
250 // Primarily, the impls will be used to populate the documentation for this
251 // type being inlined, but impls can also be used when generating
252 // documentation for primitives (no way to find those specifically).
253 if cx.populated_crate_impls.borrow_mut().insert(did.krate) {
254 csearch::each_top_level_item_of_crate(&tcx.sess.cstore,
257 populate_impls(cx, tcx, def, &mut impls)
260 fn populate_impls(cx: &DocContext, tcx: &ty::ctxt,
261 def: decoder::DefLike,
262 impls: &mut Vec<Option<clean::Item>>) {
264 decoder::DlImpl(did) => impls.push(build_impl(cx, tcx, did)),
265 decoder::DlDef(def::DefMod(did)) => {
266 csearch::each_child_of_item(&tcx.sess.cstore,
269 populate_impls(cx, tcx, def, impls)
277 impls.into_iter().filter_map(|a| a).collect()
280 fn build_impl(cx: &DocContext, tcx: &ty::ctxt,
281 did: ast::DefId) -> Option<clean::Item> {
282 if !cx.inlined.borrow_mut().as_mut().unwrap().insert(did) {
286 let associated_trait = csearch::get_impl_trait(tcx, did);
287 // If this is an impl for a #[doc(hidden)] trait, be sure to not inline it.
288 match associated_trait {
290 let trait_attrs = load_attrs(cx, tcx, t.def_id);
291 if trait_attrs.iter().any(|a| is_doc_hidden(a)) {
298 let attrs = load_attrs(cx, tcx, did);
299 let ty = ty::lookup_item_type(tcx, did);
300 let predicates = ty::lookup_predicates(tcx, did);
301 let trait_items = csearch::get_impl_items(&tcx.sess.cstore, did)
304 let did = did.def_id();
305 let impl_item = ty::impl_or_trait_item(tcx, did);
307 ty::MethodTraitItem(method) => {
308 if method.vis != ast::Public && associated_trait.is_none() {
311 if method.provided_source.is_some() {
314 let mut item = method.clean(cx);
315 item.inner = match item.inner.clone() {
316 clean::TyMethodItem(clean::TyMethod {
317 unsafety, decl, self_, generics, abi
319 clean::MethodItem(clean::Method {
327 _ => panic!("not a tymethod"),
331 ty::TypeTraitItem(ref assoc_ty) => {
332 let did = assoc_ty.def_id;
333 let type_scheme = ty::lookup_item_type(tcx, did);
334 let predicates = ty::lookup_predicates(tcx, did);
335 // Not sure the choice of ParamSpace actually matters here, because an
336 // associated type won't have generics on the LHS
337 let typedef = (type_scheme, predicates, subst::ParamSpace::TypeSpace).clean(cx);
339 name: Some(assoc_ty.name.clean(cx)),
340 inner: clean::TypedefItem(typedef),
341 source: clean::Span::empty(),
344 stability: stability::lookup(tcx, did).clean(cx),
350 let polarity = csearch::get_impl_polarity(tcx, did);
351 return Some(clean::Item {
352 inner: clean::ImplItem(clean::Impl {
353 derived: clean::detect_derived(&attrs),
354 trait_: associated_trait.clean(cx).map(|bound| {
356 clean::TraitBound(polyt, _) => polyt.trait_,
357 clean::RegionBound(..) => unreachable!(),
360 for_: ty.ty.clean(cx),
361 generics: (&ty.generics, &predicates, subst::TypeSpace).clean(cx),
363 polarity: polarity.map(|p| { p.clean(cx) }),
365 source: clean::Span::empty(),
368 visibility: Some(ast::Inherited),
369 stability: stability::lookup(tcx, did).clean(cx),
373 fn is_doc_hidden(a: &clean::Attribute) -> bool {
375 clean::List(ref name, ref inner) if *name == "doc" => {
376 inner.iter().any(|a| {
378 clean::Word(ref s) => *s == "hidden",
388 fn build_module(cx: &DocContext, tcx: &ty::ctxt,
389 did: ast::DefId) -> clean::Module {
390 let mut items = Vec::new();
391 fill_in(cx, tcx, did, &mut items);
392 return clean::Module {
397 // FIXME: this doesn't handle reexports inside the module itself.
398 // Should they be handled?
399 fn fill_in(cx: &DocContext, tcx: &ty::ctxt, did: ast::DefId,
400 items: &mut Vec<clean::Item>) {
401 csearch::each_child_of_item(&tcx.sess.cstore, did, |def, _, vis| {
403 decoder::DlDef(def::DefForeignMod(did)) => {
404 fill_in(cx, tcx, did, items);
406 decoder::DlDef(def) if vis == ast::Public => {
407 match try_inline_def(cx, tcx, def) {
408 Some(i) => items.extend(i.into_iter()),
412 decoder::DlDef(..) => {}
413 // All impls were inlined above
414 decoder::DlImpl(..) => {}
415 decoder::DlField => panic!("unimplemented field"),
421 fn build_const(cx: &DocContext, tcx: &ty::ctxt,
422 did: ast::DefId) -> clean::Constant {
423 use rustc::middle::const_eval;
424 use syntax::print::pprust;
426 let expr = const_eval::lookup_const_by_id(tcx, did).unwrap_or_else(|| {
427 panic!("expected lookup_const_by_id to succeed for {:?}", did);
429 debug!("converting constant expr {:?} to snippet", expr);
430 let sn = pprust::expr_to_string(expr);
431 debug!("got snippet {}", sn);
434 type_: ty::lookup_item_type(tcx, did).ty.clean(cx),
439 fn build_static(cx: &DocContext, tcx: &ty::ctxt,
441 mutable: bool) -> clean::Static {
443 type_: ty::lookup_item_type(tcx, did).ty.clean(cx),
444 mutability: if mutable {clean::Mutable} else {clean::Immutable},
445 expr: "\n\n\n".to_string(), // trigger the "[definition]" links