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