]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/clean/inline.rs
d243c61ddaff8ba3d91bdab8fb135e9888352d12
[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
22 use core;
23 use doctree;
24 use clean;
25
26 use super::Clean;
27
28 /// Attempt to inline the definition of a local node id into this AST.
29 ///
30 /// This function will fetch the definition of the id specified, and if it is
31 /// from another crate it will attempt to inline the documentation from the
32 /// other crate into this crate.
33 ///
34 /// This is primarily used for `pub use` statements which are, in general,
35 /// implementation details. Inlining the documentation should help provide a
36 /// better experience when reading the documentation in this use case.
37 ///
38 /// The returned value is `None` if the `id` could not be inlined, and `Some`
39 /// of a vector of items if it was successfully expanded.
40 pub fn try_inline(id: ast::NodeId) -> Option<Vec<clean::Item>> {
41     let cx = ::ctxtkey.get().unwrap();
42     let tcx = match cx.maybe_typed {
43         core::Typed(ref tycx) => tycx,
44         core::NotTyped(_) => return None,
45     };
46     let def = match tcx.def_map.borrow().find(&id) {
47         Some(def) => *def,
48         None => return None,
49     };
50     let did = def.def_id();
51     if ast_util::is_local(did) { return None }
52     try_inline_def(&**cx, tcx, def)
53 }
54
55 fn try_inline_def(cx: &core::DocContext,
56                   tcx: &ty::ctxt,
57                   def: def::Def) -> Option<Vec<clean::Item>> {
58     let mut ret = Vec::new();
59     let did = def.def_id();
60     let inner = match def {
61         def::DefTrait(did) => {
62             record_extern_fqn(cx, did, clean::TypeTrait);
63             clean::TraitItem(build_external_trait(tcx, did))
64         }
65         def::DefFn(did, style) => {
66             // If this function is a tuple struct constructor, we just skip it
67             if csearch::get_tuple_struct_definition_if_ctor(&tcx.sess.cstore,
68                                                             did).is_some() {
69                 return None
70             }
71             record_extern_fqn(cx, did, clean::TypeFunction);
72             clean::FunctionItem(build_external_function(tcx, did, style))
73         }
74         def::DefStruct(did) => {
75             record_extern_fqn(cx, did, clean::TypeStruct);
76             ret.extend(build_impls(cx, tcx, did).move_iter());
77             clean::StructItem(build_struct(tcx, did))
78         }
79         def::DefTy(did) => {
80             record_extern_fqn(cx, did, clean::TypeEnum);
81             ret.extend(build_impls(cx, tcx, did).move_iter());
82             build_type(tcx, did)
83         }
84         // Assume that the enum type is reexported next to the variant, and
85         // variants don't show up in documentation specially.
86         def::DefVariant(..) => return Some(Vec::new()),
87         def::DefMod(did) => {
88             record_extern_fqn(cx, did, clean::TypeModule);
89             clean::ModuleItem(build_module(cx, tcx, did))
90         }
91         def::DefStatic(did, mtbl) => {
92             record_extern_fqn(cx, did, clean::TypeStatic);
93             clean::StaticItem(build_static(tcx, did, mtbl))
94         }
95         _ => return None,
96     };
97     let fqn = csearch::get_item_path(tcx, did);
98     cx.inlined.borrow_mut().get_mut_ref().insert(did);
99     ret.push(clean::Item {
100         source: clean::Span::empty(),
101         name: Some(fqn.last().unwrap().to_str()),
102         attrs: load_attrs(tcx, did),
103         inner: inner,
104         visibility: Some(ast::Public),
105         def_id: did,
106     });
107     Some(ret)
108 }
109
110 pub fn load_attrs(tcx: &ty::ctxt, did: ast::DefId) -> Vec<clean::Attribute> {
111     let mut attrs = Vec::new();
112     csearch::get_item_attrs(&tcx.sess.cstore, did, |v| {
113         attrs.extend(v.move_iter().map(|mut a| {
114             // FIXME this isn't quite always true, it's just true about 99% of
115             //       the time when dealing with documentation. For example,
116             //       this would treat doc comments of the form `#[doc = "foo"]`
117             //       incorrectly.
118             if a.name().get() == "doc" && a.value_str().is_some() {
119                 a.node.is_sugared_doc = true;
120             }
121             a.clean()
122         }));
123     });
124     attrs
125 }
126
127 /// Record an external fully qualified name in the external_paths cache.
128 ///
129 /// These names are used later on by HTML rendering to generate things like
130 /// source links back to the original item.
131 pub fn record_extern_fqn(cx: &core::DocContext,
132                          did: ast::DefId,
133                          kind: clean::TypeKind) {
134     match cx.maybe_typed {
135         core::Typed(ref tcx) => {
136             let fqn = csearch::get_item_path(tcx, did);
137             let fqn = fqn.move_iter().map(|i| i.to_str()).collect();
138             cx.external_paths.borrow_mut().get_mut_ref().insert(did, (fqn, kind));
139         }
140         core::NotTyped(..) => {}
141     }
142 }
143
144 pub fn build_external_trait(tcx: &ty::ctxt, did: ast::DefId) -> clean::Trait {
145     let def = ty::lookup_trait_def(tcx, did);
146     let methods = ty::trait_methods(tcx, did).clean();
147     let provided = ty::provided_trait_methods(tcx, did);
148     let mut methods = methods.move_iter().map(|meth| {
149         if provided.iter().any(|a| a.def_id == meth.def_id) {
150             clean::Provided(meth)
151         } else {
152             clean::Required(meth)
153         }
154     });
155     let supertraits = ty::trait_supertraits(tcx, did);
156     let mut parents = supertraits.iter().map(|i| {
157         match i.clean() {
158             clean::TraitBound(ty) => ty,
159             clean::RegionBound => unreachable!()
160         }
161     });
162
163     clean::Trait {
164         generics: def.generics.clean(),
165         methods: methods.collect(),
166         parents: parents.collect()
167     }
168 }
169
170 fn build_external_function(tcx: &ty::ctxt,
171                            did: ast::DefId,
172                            style: ast::FnStyle) -> clean::Function {
173     let t = ty::lookup_item_type(tcx, did);
174     clean::Function {
175         decl: match ty::get(t.ty).sty {
176             ty::ty_bare_fn(ref f) => (did, &f.sig).clean(),
177             _ => fail!("bad function"),
178         },
179         generics: t.generics.clean(),
180         fn_style: style,
181     }
182 }
183
184 fn build_struct(tcx: &ty::ctxt, did: ast::DefId) -> clean::Struct {
185     use syntax::parse::token::special_idents::unnamed_field;
186
187     let t = ty::lookup_item_type(tcx, did);
188     let fields = ty::lookup_struct_fields(tcx, did);
189
190     clean::Struct {
191         struct_type: match fields.as_slice() {
192             [] => doctree::Unit,
193             [ref f] if f.name == unnamed_field.name => doctree::Newtype,
194             [ref f, ..] if f.name == unnamed_field.name => doctree::Tuple,
195             _ => doctree::Plain,
196         },
197         generics: t.generics.clean(),
198         fields: fields.iter().map(|f| f.clean()).collect(),
199         fields_stripped: false,
200     }
201 }
202
203 fn build_type(tcx: &ty::ctxt, did: ast::DefId) -> clean::ItemEnum {
204     let t = ty::lookup_item_type(tcx, did);
205     match ty::get(t.ty).sty {
206         ty::ty_enum(edid, _) if !csearch::is_typedef(&tcx.sess.cstore, did) => {
207             return clean::EnumItem(clean::Enum {
208                 generics: t.generics.clean(),
209                 variants_stripped: false,
210                 variants: ty::enum_variants(tcx, edid).clean(),
211             })
212         }
213         _ => {}
214     }
215
216     clean::TypedefItem(clean::Typedef {
217         type_: t.ty.clean(),
218         generics: t.generics.clean(),
219     })
220 }
221
222 fn build_impls(cx: &core::DocContext,
223                tcx: &ty::ctxt,
224                did: ast::DefId) -> Vec<clean::Item> {
225     ty::populate_implementations_for_type_if_necessary(tcx, did);
226     let mut impls = Vec::new();
227
228     match tcx.inherent_impls.borrow().find(&did) {
229         None => {}
230         Some(i) => {
231             impls.extend(i.borrow().iter().map(|&did| { build_impl(cx, tcx, did) }));
232         }
233     }
234
235     // If this is the first time we've inlined something from this crate, then
236     // we inline *all* impls from the crate into this crate. Note that there's
237     // currently no way for us to filter this based on type, and we likely need
238     // many impls for a variety of reasons.
239     //
240     // Primarily, the impls will be used to populate the documentation for this
241     // type being inlined, but impls can also be used when generating
242     // documentation for primitives (no way to find those specifically).
243     if cx.populated_crate_impls.borrow_mut().insert(did.krate) {
244         csearch::each_top_level_item_of_crate(&tcx.sess.cstore,
245                                               did.krate,
246                                               |def, _, _| {
247             populate_impls(cx, tcx, def, &mut impls)
248         });
249
250         fn populate_impls(cx: &core::DocContext,
251                           tcx: &ty::ctxt,
252                           def: decoder::DefLike,
253                           impls: &mut Vec<Option<clean::Item>>) {
254             match def {
255                 decoder::DlImpl(did) => impls.push(build_impl(cx, tcx, did)),
256                 decoder::DlDef(def::DefMod(did)) => {
257                     csearch::each_child_of_item(&tcx.sess.cstore,
258                                                 did,
259                                                 |def, _, _| {
260                         populate_impls(cx, tcx, def, impls)
261                     })
262                 }
263                 _ => {}
264             }
265         }
266     }
267
268     impls.move_iter().filter_map(|a| a).collect()
269 }
270
271 fn build_impl(cx: &core::DocContext,
272               tcx: &ty::ctxt,
273               did: ast::DefId) -> Option<clean::Item> {
274     if !cx.inlined.borrow_mut().get_mut_ref().insert(did) {
275         return None
276     }
277
278     let associated_trait = csearch::get_impl_trait(tcx, did);
279     let attrs = load_attrs(tcx, did);
280     let ty = ty::lookup_item_type(tcx, did);
281     let methods = csearch::get_impl_methods(&tcx.sess.cstore,
282                                             did).iter().filter_map(|did| {
283         let method = ty::method(tcx, *did);
284         if method.vis != ast::Public && associated_trait.is_none() {
285             return None
286         }
287         let mut item = ty::method(tcx, *did).clean();
288         item.inner = match item.inner.clone() {
289             clean::TyMethodItem(clean::TyMethod {
290                 fn_style, decl, self_, generics
291             }) => {
292                 clean::MethodItem(clean::Method {
293                     fn_style: fn_style,
294                     decl: decl,
295                     self_: self_,
296                     generics: generics,
297                 })
298             }
299             _ => fail!("not a tymethod"),
300         };
301         Some(item)
302     }).collect();
303     Some(clean::Item {
304         inner: clean::ImplItem(clean::Impl {
305             derived: clean::detect_derived(attrs.as_slice()),
306             trait_: associated_trait.clean().map(|bound| {
307                 match bound {
308                     clean::TraitBound(ty) => ty,
309                     clean::RegionBound => unreachable!(),
310                 }
311             }),
312             for_: ty.ty.clean(),
313             generics: ty.generics.clean(),
314             methods: methods,
315         }),
316         source: clean::Span::empty(),
317         name: None,
318         attrs: attrs,
319         visibility: Some(ast::Inherited),
320         def_id: did,
321     })
322 }
323
324 fn build_module(cx: &core::DocContext, tcx: &ty::ctxt,
325                 did: ast::DefId) -> clean::Module {
326     let mut items = Vec::new();
327
328     // FIXME: this doesn't handle reexports inside the module itself.
329     //        Should they be handled?
330     csearch::each_child_of_item(&tcx.sess.cstore, did, |def, _, vis| {
331         if vis != ast::Public { return }
332         match def {
333             decoder::DlDef(def) => {
334                 match try_inline_def(cx, tcx, def) {
335                     Some(i) => items.extend(i.move_iter()),
336                     None => {}
337                 }
338             }
339             // All impls were inlined above
340             decoder::DlImpl(..) => {}
341             decoder::DlField => fail!("unimplemented field"),
342         }
343     });
344
345     clean::Module {
346         items: items,
347         is_crate: false,
348     }
349 }
350
351 fn build_static(tcx: &ty::ctxt,
352                 did: ast::DefId,
353                 mutable: bool) -> clean::Static {
354     clean::Static {
355         type_: ty::lookup_item_type(tcx, did).ty.clean(),
356         mutability: if mutable {clean::Mutable} else {clean::Immutable},
357         expr: "\n\n\n".to_string(), // trigger the "[definition]" links
358     }
359 }