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