]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/inline.rs
rollup merge of #21075: iKevinY/intro-changes
[rust.git] / src / librustdoc / clean / inline.rs
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.
4 //
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.
10
11 //! Support for inlining external documentation into the current AST.
12
13 use syntax::ast;
14 use syntax::ast_util;
15 use syntax::attr::AttrMetaMethods;
16
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;
23
24 use core::DocContext;
25 use doctree;
26 use clean;
27
28 use super::Clean;
29
30 /// Attempt to inline the definition of a local node id into this AST.
31 ///
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.
35 ///
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.
39 ///
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() {
45         Some(tcx) => tcx,
46         None => return None,
47     };
48     let def = match tcx.def_map.borrow().get(&id) {
49         Some(def) => *def,
50         None => return None,
51     };
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| {
56             match into {
57                 Some(into) if item.name.is_some() => {
58                     item.name = Some(into.clean(cx));
59                 }
60                 _ => {}
61             }
62             item
63         }).collect()
64     })
65 }
66
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))
75         }
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))
80         }
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))
85         }
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)
90         }
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)
95         }
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()),
99         def::DefMod(did) => {
100             record_extern_fqn(cx, did, clean::TypeModule);
101             clean::ModuleItem(build_module(cx, tcx, did))
102         }
103         def::DefStatic(did, mtbl) => {
104             record_extern_fqn(cx, did, clean::TypeStatic);
105             clean::StaticItem(build_static(cx, tcx, did, mtbl))
106         }
107         def::DefConst(did) => {
108             record_extern_fqn(cx, did, clean::TypeConst);
109             clean::ConstantItem(build_const(cx, tcx, did))
110         }
111         _ => return None,
112     };
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),
119         inner: inner,
120         visibility: Some(ast::Public),
121         stability: stability::lookup(tcx, did).clean(cx),
122         def_id: did,
123     });
124     Some(ret)
125 }
126
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()
131 }
132
133 /// Record an external fully qualified name in the external_paths cache.
134 ///
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) {
138     match cx.tcx_opt() {
139         Some(tcx) => {
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));
143         }
144         None => {}
145     }
146 }
147
148 pub fn build_external_trait(cx: &DocContext, tcx: &ty::ctxt,
149                             did: ast::DefId) -> clean::Trait {
150     let def = ty::lookup_trait_def(tcx, did);
151     let trait_items = ty::trait_items(tcx, did).clean(cx);
152     let provided = ty::provided_trait_methods(tcx, did);
153     let items = trait_items.into_iter().map(|trait_item| {
154         if provided.iter().any(|a| a.def_id == trait_item.def_id) {
155             clean::ProvidedMethod(trait_item)
156         } else {
157             clean::RequiredMethod(trait_item)
158         }
159     });
160     let trait_def = ty::lookup_trait_def(tcx, did);
161     let bounds = trait_def.bounds.clean(cx);
162     clean::Trait {
163         unsafety: def.unsafety,
164         generics: (&def.generics, subst::TypeSpace).clean(cx),
165         items: items.collect(),
166         bounds: bounds,
167     }
168 }
169
170 fn build_external_function(cx: &DocContext, tcx: &ty::ctxt, did: ast::DefId) -> clean::Function {
171     let t = ty::lookup_item_type(tcx, did);
172     let (decl, style) = match t.ty.sty {
173         ty::ty_bare_fn(_, ref f) => ((did, &f.sig).clean(cx), f.unsafety),
174         _ => panic!("bad function"),
175     };
176     clean::Function {
177         decl: decl,
178         generics: (&t.generics, subst::FnSpace).clean(cx),
179         unsafety: style,
180     }
181 }
182
183 fn build_struct(cx: &DocContext, tcx: &ty::ctxt, did: ast::DefId) -> clean::Struct {
184     use syntax::parse::token::special_idents::unnamed_field;
185
186     let t = ty::lookup_item_type(tcx, did);
187     let fields = ty::lookup_struct_fields(tcx, did);
188
189     clean::Struct {
190         struct_type: match fields.as_slice() {
191             [] => doctree::Unit,
192             [ref f] if f.name == unnamed_field.name => doctree::Newtype,
193             [ref f, ..] if f.name == unnamed_field.name => doctree::Tuple,
194             _ => doctree::Plain,
195         },
196         generics: (&t.generics, subst::TypeSpace).clean(cx),
197         fields: fields.clean(cx),
198         fields_stripped: false,
199     }
200 }
201
202 fn build_type(cx: &DocContext, tcx: &ty::ctxt, did: ast::DefId) -> clean::ItemEnum {
203     let t = ty::lookup_item_type(tcx, did);
204     match t.ty.sty {
205         ty::ty_enum(edid, _) if !csearch::is_typedef(&tcx.sess.cstore, did) => {
206             return clean::EnumItem(clean::Enum {
207                 generics: (&t.generics, subst::TypeSpace).clean(cx),
208                 variants_stripped: false,
209                 variants: ty::enum_variants(tcx, edid).clean(cx),
210             })
211         }
212         _ => {}
213     }
214
215     clean::TypedefItem(clean::Typedef {
216         type_: t.ty.clean(cx),
217         generics: (&t.generics, subst::TypeSpace).clean(cx),
218     })
219 }
220
221 fn build_impls(cx: &DocContext, tcx: &ty::ctxt,
222                did: ast::DefId) -> Vec<clean::Item> {
223     ty::populate_implementations_for_type_if_necessary(tcx, did);
224     let mut impls = Vec::new();
225
226     match tcx.inherent_impls.borrow().get(&did) {
227         None => {}
228         Some(i) => {
229             impls.extend(i.iter().map(|&did| { build_impl(cx, tcx, did) }));
230         }
231     }
232
233     // If this is the first time we've inlined something from this crate, then
234     // we inline *all* impls from the crate into this crate. Note that there's
235     // currently no way for us to filter this based on type, and we likely need
236     // many impls for a variety of reasons.
237     //
238     // Primarily, the impls will be used to populate the documentation for this
239     // type being inlined, but impls can also be used when generating
240     // documentation for primitives (no way to find those specifically).
241     if cx.populated_crate_impls.borrow_mut().insert(did.krate) {
242         csearch::each_top_level_item_of_crate(&tcx.sess.cstore,
243                                               did.krate,
244                                               |def, _, _| {
245             populate_impls(cx, tcx, def, &mut impls)
246         });
247
248         fn populate_impls(cx: &DocContext, tcx: &ty::ctxt,
249                           def: decoder::DefLike,
250                           impls: &mut Vec<Option<clean::Item>>) {
251             match def {
252                 decoder::DlImpl(did) => impls.push(build_impl(cx, tcx, did)),
253                 decoder::DlDef(def::DefMod(did)) => {
254                     csearch::each_child_of_item(&tcx.sess.cstore,
255                                                 did,
256                                                 |def, _, _| {
257                         populate_impls(cx, tcx, def, impls)
258                     })
259                 }
260                 _ => {}
261             }
262         }
263     }
264
265     impls.into_iter().filter_map(|a| a).collect()
266 }
267
268 fn build_impl(cx: &DocContext, tcx: &ty::ctxt,
269               did: ast::DefId) -> Option<clean::Item> {
270     if !cx.inlined.borrow_mut().as_mut().unwrap().insert(did) {
271         return None
272     }
273
274     let associated_trait = csearch::get_impl_trait(tcx, did);
275     // If this is an impl for a #[doc(hidden)] trait, be sure to not inline it.
276     match associated_trait {
277         Some(ref t) => {
278             let trait_attrs = load_attrs(cx, tcx, t.def_id);
279             if trait_attrs.iter().any(|a| is_doc_hidden(a)) {
280                 return None
281             }
282         }
283         None => {}
284     }
285
286     let attrs = load_attrs(cx, tcx, did);
287     let ty = ty::lookup_item_type(tcx, did);
288     let trait_items = csearch::get_impl_items(&tcx.sess.cstore, did)
289             .iter()
290             .filter_map(|did| {
291         let did = did.def_id();
292         let impl_item = ty::impl_or_trait_item(tcx, did);
293         match impl_item {
294             ty::MethodTraitItem(method) => {
295                 if method.vis != ast::Public && associated_trait.is_none() {
296                     return None
297                 }
298                 let mut item = method.clean(cx);
299                 item.inner = match item.inner.clone() {
300                     clean::TyMethodItem(clean::TyMethod {
301                         unsafety, decl, self_, generics
302                     }) => {
303                         clean::MethodItem(clean::Method {
304                             unsafety: unsafety,
305                             decl: decl,
306                             self_: self_,
307                             generics: generics,
308                         })
309                     }
310                     _ => panic!("not a tymethod"),
311                 };
312                 Some(item)
313             }
314             ty::TypeTraitItem(_) => {
315                 // FIXME(pcwalton): Implement.
316                 None
317             }
318         }
319     }).collect();
320     return Some(clean::Item {
321         inner: clean::ImplItem(clean::Impl {
322             derived: clean::detect_derived(attrs.as_slice()),
323             trait_: associated_trait.clean(cx).map(|bound| {
324                 match bound {
325                     clean::TraitBound(polyt, _) => polyt.trait_,
326                     clean::RegionBound(..) => unreachable!(),
327                 }
328             }),
329             for_: ty.ty.clean(cx),
330             generics: (&ty.generics, subst::TypeSpace).clean(cx),
331             items: trait_items,
332         }),
333         source: clean::Span::empty(),
334         name: None,
335         attrs: attrs,
336         visibility: Some(ast::Inherited),
337         stability: stability::lookup(tcx, did).clean(cx),
338         def_id: did,
339     });
340
341     fn is_doc_hidden(a: &clean::Attribute) -> bool {
342         match *a {
343             clean::List(ref name, ref inner) if *name == "doc" => {
344                 inner.iter().any(|a| {
345                     match *a {
346                         clean::Word(ref s) => *s == "hidden",
347                         _ => false,
348                     }
349                 })
350             }
351             _ => false
352         }
353     }
354 }
355
356 fn build_module(cx: &DocContext, tcx: &ty::ctxt,
357                 did: ast::DefId) -> clean::Module {
358     let mut items = Vec::new();
359     fill_in(cx, tcx, did, &mut items);
360     return clean::Module {
361         items: items,
362         is_crate: false,
363     };
364
365     // FIXME: this doesn't handle reexports inside the module itself.
366     //        Should they be handled?
367     fn fill_in(cx: &DocContext, tcx: &ty::ctxt, did: ast::DefId,
368                items: &mut Vec<clean::Item>) {
369         csearch::each_child_of_item(&tcx.sess.cstore, did, |def, _, vis| {
370             match def {
371                 decoder::DlDef(def::DefForeignMod(did)) => {
372                     fill_in(cx, tcx, did, items);
373                 }
374                 decoder::DlDef(def) if vis == ast::Public => {
375                     match try_inline_def(cx, tcx, def) {
376                         Some(i) => items.extend(i.into_iter()),
377                         None => {}
378                     }
379                 }
380                 decoder::DlDef(..) => {}
381                 // All impls were inlined above
382                 decoder::DlImpl(..) => {}
383                 decoder::DlField => panic!("unimplemented field"),
384             }
385         });
386     }
387 }
388
389 fn build_const(cx: &DocContext, tcx: &ty::ctxt,
390                did: ast::DefId) -> clean::Constant {
391     use rustc::middle::const_eval;
392     use syntax::print::pprust;
393
394     let expr = const_eval::lookup_const_by_id(tcx, did).unwrap_or_else(|| {
395         panic!("expected lookup_const_by_id to succeed for {:?}", did);
396     });
397     debug!("converting constant expr {:?} to snippet", expr);
398     let sn = pprust::expr_to_string(expr);
399     debug!("got snippet {}", sn);
400
401     clean::Constant {
402         type_: ty::lookup_item_type(tcx, did).ty.clean(cx),
403         expr: sn
404     }
405 }
406
407 fn build_static(cx: &DocContext, tcx: &ty::ctxt,
408                 did: ast::DefId,
409                 mutable: bool) -> clean::Static {
410     clean::Static {
411         type_: ty::lookup_item_type(tcx, did).ty.clean(cx),
412         mutability: if mutable {clean::Mutable} else {clean::Immutable},
413         expr: "\n\n\n".to_string(), // trigger the "[definition]" links
414     }
415 }