]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/visit_ast.rs
00fe0134f00ee356907c2f725e4f7adf4116c9cb
[rust.git] / src / librustdoc / visit_ast.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 //! Rust AST Visitor. Extracts useful information and massages it into a form
12 //! usable for clean
13
14 use syntax::abi;
15 use syntax::ast;
16 use syntax::ast_util;
17 use syntax::ast_map;
18 use syntax::attr::AttrMetaMethods;
19 use syntax::codemap::Span;
20
21 use std::gc::{Gc, GC};
22
23 use core;
24 use doctree::*;
25
26 pub struct RustdocVisitor<'a> {
27     pub module: Module,
28     pub attrs: Vec<ast::Attribute>,
29     pub cx: &'a core::DocContext,
30     pub analysis: Option<&'a core::CrateAnalysis>,
31 }
32
33 impl<'a> RustdocVisitor<'a> {
34     pub fn new<'b>(cx: &'b core::DocContext,
35                    analysis: Option<&'b core::CrateAnalysis>) -> RustdocVisitor<'b> {
36         RustdocVisitor {
37             module: Module::new(None),
38             attrs: Vec::new(),
39             cx: cx,
40             analysis: analysis,
41         }
42     }
43
44     pub fn visit(&mut self, krate: &ast::Crate) {
45         self.attrs = krate.attrs.iter().map(|x| (*x).clone()).collect();
46
47         self.module = self.visit_mod_contents(krate.span,
48                                               krate.attrs
49                                                    .iter()
50                                                    .map(|x| *x)
51                                                    .collect(),
52                                               ast::Public,
53                                               ast::CRATE_NODE_ID,
54                                               &krate.module,
55                                               None);
56         self.module.is_crate = true;
57     }
58
59     pub fn visit_struct_def(&mut self, item: &ast::Item, sd: Gc<ast::StructDef>,
60                             generics: &ast::Generics) -> Struct {
61         debug!("Visiting struct");
62         let struct_type = struct_type_from_def(&*sd);
63         Struct {
64             id: item.id,
65             struct_type: struct_type,
66             name: item.ident,
67             vis: item.vis,
68             attrs: item.attrs.iter().map(|x| *x).collect(),
69             generics: generics.clone(),
70             fields: sd.fields.iter().map(|x| (*x).clone()).collect(),
71             where: item.span
72         }
73     }
74
75     pub fn visit_enum_def(&mut self, it: &ast::Item, def: &ast::EnumDef,
76                           params: &ast::Generics) -> Enum {
77         debug!("Visiting enum");
78         let mut vars: Vec<Variant> = Vec::new();
79         for x in def.variants.iter() {
80             vars.push(Variant {
81                 name: x.node.name,
82                 attrs: x.node.attrs.iter().map(|x| *x).collect(),
83                 vis: x.node.vis,
84                 id: x.node.id,
85                 kind: x.node.kind.clone(),
86                 where: x.span,
87             });
88         }
89         Enum {
90             name: it.ident,
91             variants: vars,
92             vis: it.vis,
93             generics: params.clone(),
94             attrs: it.attrs.iter().map(|x| *x).collect(),
95             id: it.id,
96             where: it.span,
97         }
98     }
99
100     pub fn visit_fn(&mut self, item: &ast::Item, fd: &ast::FnDecl,
101                     fn_style: &ast::FnStyle, _abi: &abi::Abi,
102                     gen: &ast::Generics) -> Function {
103         debug!("Visiting fn");
104         Function {
105             id: item.id,
106             vis: item.vis,
107             attrs: item.attrs.iter().map(|x| *x).collect(),
108             decl: fd.clone(),
109             name: item.ident,
110             where: item.span,
111             generics: gen.clone(),
112             fn_style: *fn_style,
113         }
114     }
115
116     pub fn visit_mod_contents(&mut self, span: Span, attrs: Vec<ast::Attribute> ,
117                               vis: ast::Visibility, id: ast::NodeId,
118                               m: &ast::Mod,
119                               name: Option<ast::Ident>) -> Module {
120         let mut om = Module::new(name);
121         for item in m.view_items.iter() {
122             self.visit_view_item(item, &mut om);
123         }
124         om.where_outer = span;
125         om.where_inner = m.inner;
126         om.attrs = attrs;
127         om.vis = vis;
128         om.id = id;
129         for i in m.items.iter() {
130             self.visit_item(&**i, &mut om);
131         }
132         om
133     }
134
135     pub fn visit_view_item(&mut self, item: &ast::ViewItem, om: &mut Module) {
136         if item.vis != ast::Public {
137             return om.view_items.push(item.clone());
138         }
139         let please_inline = item.attrs.iter().any(|item| {
140             match item.meta_item_list() {
141                 Some(list) => {
142                     list.iter().any(|i| i.name().get() == "inline")
143                 }
144                 None => false,
145             }
146         });
147         let item = match item.node {
148             ast::ViewItemUse(ref vpath) => {
149                 match self.visit_view_path(*vpath, om, please_inline) {
150                     None => return,
151                     Some(path) => {
152                         ast::ViewItem {
153                             node: ast::ViewItemUse(path),
154                             .. item.clone()
155                         }
156                     }
157                 }
158             }
159             ast::ViewItemExternCrate(..) => item.clone()
160         };
161         om.view_items.push(item);
162     }
163
164     fn visit_view_path(&mut self, path: Gc<ast::ViewPath>,
165                        om: &mut Module,
166                        please_inline: bool) -> Option<Gc<ast::ViewPath>> {
167         match path.node {
168             ast::ViewPathSimple(_, _, id) => {
169                 if self.resolve_id(id, false, om, please_inline) { return None }
170             }
171             ast::ViewPathList(ref p, ref paths, ref b) => {
172                 let mut mine = Vec::new();
173                 for path in paths.iter() {
174                     if !self.resolve_id(path.node.id, false, om, please_inline) {
175                         mine.push(path.clone());
176                     }
177                 }
178
179                 if mine.len() == 0 { return None }
180                 return Some(box(GC) ::syntax::codemap::Spanned {
181                     node: ast::ViewPathList(p.clone(), mine, b.clone()),
182                     span: path.span,
183                 })
184             }
185
186             // these are feature gated anyway
187             ast::ViewPathGlob(_, id) => {
188                 if self.resolve_id(id, true, om, please_inline) { return None }
189             }
190         }
191         return Some(path);
192     }
193
194     fn resolve_id(&mut self, id: ast::NodeId, glob: bool,
195                   om: &mut Module, please_inline: bool) -> bool {
196         let tcx = match self.cx.maybe_typed {
197             core::Typed(ref tcx) => tcx,
198             core::NotTyped(_) => return false
199         };
200         let def = tcx.def_map.borrow().get(&id).def_id();
201         if !ast_util::is_local(def) { return false }
202         let analysis = match self.analysis {
203             Some(analysis) => analysis, None => return false
204         };
205         if !please_inline && analysis.public_items.contains(&def.node) {
206             return false
207         }
208
209         match tcx.map.get(def.node) {
210             ast_map::NodeItem(it) => {
211                 if glob {
212                     match it.node {
213                         ast::ItemMod(ref m) => {
214                             for vi in m.view_items.iter() {
215                                 self.visit_view_item(vi, om);
216                             }
217                             for i in m.items.iter() {
218                                 self.visit_item(&**i, om);
219                             }
220                         }
221                         _ => { fail!("glob not mapped to a module"); }
222                     }
223                 } else {
224                     self.visit_item(&*it, om);
225                 }
226                 true
227             }
228             _ => false,
229         }
230     }
231
232     pub fn visit_item(&mut self, item: &ast::Item, om: &mut Module) {
233         debug!("Visiting item {:?}", item);
234         match item.node {
235             ast::ItemMod(ref m) => {
236                 om.mods.push(self.visit_mod_contents(item.span,
237                                                      item.attrs
238                                                          .iter()
239                                                          .map(|x| *x)
240                                                          .collect(),
241                                                      item.vis,
242                                                      item.id,
243                                                      m,
244                                                      Some(item.ident)));
245             },
246             ast::ItemEnum(ref ed, ref gen) =>
247                 om.enums.push(self.visit_enum_def(item, ed, gen)),
248             ast::ItemStruct(sd, ref gen) =>
249                 om.structs.push(self.visit_struct_def(item, sd, gen)),
250             ast::ItemFn(ref fd, ref pur, ref abi, ref gen, _) =>
251                 om.fns.push(self.visit_fn(item, &**fd, pur, abi, gen)),
252             ast::ItemTy(ty, ref gen) => {
253                 let t = Typedef {
254                     ty: ty,
255                     gen: gen.clone(),
256                     name: item.ident,
257                     id: item.id,
258                     attrs: item.attrs.iter().map(|x| *x).collect(),
259                     where: item.span,
260                     vis: item.vis,
261                 };
262                 om.typedefs.push(t);
263             },
264             ast::ItemStatic(ty, ref mut_, ref exp) => {
265                 let s = Static {
266                     type_: ty,
267                     mutability: mut_.clone(),
268                     expr: exp.clone(),
269                     id: item.id,
270                     name: item.ident,
271                     attrs: item.attrs.iter().map(|x| *x).collect(),
272                     where: item.span,
273                     vis: item.vis,
274                 };
275                 om.statics.push(s);
276             },
277             ast::ItemTrait(ref gen, _, ref tr, ref met) => {
278                 let t = Trait {
279                     name: item.ident,
280                     methods: met.iter().map(|x| (*x).clone()).collect(),
281                     generics: gen.clone(),
282                     parents: tr.iter().map(|x| (*x).clone()).collect(),
283                     id: item.id,
284                     attrs: item.attrs.iter().map(|x| *x).collect(),
285                     where: item.span,
286                     vis: item.vis,
287                 };
288                 om.traits.push(t);
289             },
290             ast::ItemImpl(ref gen, ref tr, ty, ref meths) => {
291                 let i = Impl {
292                     generics: gen.clone(),
293                     trait_: tr.clone(),
294                     for_: ty,
295                     methods: meths.iter().map(|x| *x).collect(),
296                     attrs: item.attrs.iter().map(|x| *x).collect(),
297                     id: item.id,
298                     where: item.span,
299                     vis: item.vis,
300                 };
301                 om.impls.push(i);
302             },
303             ast::ItemForeignMod(ref fm) => {
304                 om.foreigns.push(fm.clone());
305             }
306             ast::ItemMac(ref _m) => {
307                 om.macros.push(Macro {
308                     id: item.id,
309                     attrs: item.attrs.iter().map(|x| *x).collect(),
310                     name: item.ident,
311                     where: item.span,
312                 })
313             }
314         }
315     }
316 }