]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/visit_ast.rs
b6c93bf00af5fa1f8255a9d9fa2a3fe95485f159
[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 std::collections::HashSet;
15 use std::mem;
16
17 use syntax::abi;
18 use syntax::ast;
19 use syntax::attr;
20 use syntax::attr::AttrMetaMethods;
21 use syntax::codemap::Span;
22
23 use rustc::front::map as hir_map;
24 use rustc::middle::stability;
25
26 use rustc_front::hir;
27
28 use core;
29 use doctree::*;
30
31 // looks to me like the first two of these are actually
32 // output parameters, maybe only mutated once; perhaps
33 // better simply to have the visit method return a tuple
34 // containing them?
35
36 // also, is there some reason that this doesn't use the 'visit'
37 // framework from syntax?
38
39 pub struct RustdocVisitor<'a, 'tcx: 'a> {
40     pub module: Module,
41     pub attrs: Vec<ast::Attribute>,
42     pub cx: &'a core::DocContext<'a, 'tcx>,
43     pub analysis: Option<&'a core::CrateAnalysis>,
44     view_item_stack: HashSet<ast::NodeId>,
45     inlining_from_glob: bool,
46 }
47
48 impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
49     pub fn new(cx: &'a core::DocContext<'a, 'tcx>,
50                analysis: Option<&'a core::CrateAnalysis>) -> RustdocVisitor<'a, 'tcx> {
51         // If the root is reexported, terminate all recursion.
52         let mut stack = HashSet::new();
53         stack.insert(ast::CRATE_NODE_ID);
54         RustdocVisitor {
55             module: Module::new(None),
56             attrs: Vec::new(),
57             cx: cx,
58             analysis: analysis,
59             view_item_stack: stack,
60             inlining_from_glob: false,
61         }
62     }
63
64     fn stability(&self, id: ast::NodeId) -> Option<attr::Stability> {
65         self.cx.tcx_opt().and_then(|tcx| {
66             self.cx.map.opt_local_def_id(id)
67                        .and_then(|def_id| stability::lookup(tcx, def_id))
68                        .cloned()
69         })
70     }
71
72     pub fn visit(&mut self, krate: &hir::Crate) {
73         self.attrs = krate.attrs.clone();
74
75         self.module = self.visit_mod_contents(krate.span,
76                                               krate.attrs.clone(),
77                                               hir::Public,
78                                               ast::CRATE_NODE_ID,
79                                               &krate.module,
80                                               None);
81         // attach the crate's exported macros to the top-level module:
82         self.module.macros = krate.exported_macros.iter()
83             .map(|def| self.visit_macro(def)).collect();
84         self.module.is_crate = true;
85     }
86
87     pub fn visit_variant_data(&mut self, item: &hir::Item,
88                             name: ast::Name, sd: &hir::VariantData,
89                             generics: &hir::Generics) -> Struct {
90         debug!("Visiting struct");
91         let struct_type = struct_type_from_def(&*sd);
92         Struct {
93             id: item.id,
94             struct_type: struct_type,
95             name: name,
96             vis: item.vis,
97             stab: self.stability(item.id),
98             attrs: item.attrs.clone(),
99             generics: generics.clone(),
100             fields: sd.fields().iter().cloned().collect(),
101             whence: item.span
102         }
103     }
104
105     pub fn visit_enum_def(&mut self, it: &hir::Item,
106                           name: ast::Name, def: &hir::EnumDef,
107                           params: &hir::Generics) -> Enum {
108         debug!("Visiting enum");
109         Enum {
110             name: name,
111             variants: def.variants.iter().map(|v| Variant {
112                 name: v.node.name,
113                 attrs: v.node.attrs.clone(),
114                 stab: self.stability(v.node.data.id()),
115                 def: v.node.data.clone(),
116                 whence: v.span,
117             }).collect(),
118             vis: it.vis,
119             stab: self.stability(it.id),
120             generics: params.clone(),
121             attrs: it.attrs.clone(),
122             id: it.id,
123             whence: it.span,
124         }
125     }
126
127     pub fn visit_fn(&mut self, item: &hir::Item,
128                     name: ast::Name, fd: &hir::FnDecl,
129                     unsafety: &hir::Unsafety,
130                     constness: hir::Constness,
131                     abi: &abi::Abi,
132                     gen: &hir::Generics) -> Function {
133         debug!("Visiting fn");
134         Function {
135             id: item.id,
136             vis: item.vis,
137             stab: self.stability(item.id),
138             attrs: item.attrs.clone(),
139             decl: fd.clone(),
140             name: name,
141             whence: item.span,
142             generics: gen.clone(),
143             unsafety: *unsafety,
144             constness: constness,
145             abi: *abi,
146         }
147     }
148
149     pub fn visit_mod_contents(&mut self, span: Span, attrs: Vec<ast::Attribute> ,
150                               vis: hir::Visibility, id: ast::NodeId,
151                               m: &hir::Mod,
152                               name: Option<ast::Name>) -> Module {
153         let mut om = Module::new(name);
154         om.where_outer = span;
155         om.where_inner = m.inner;
156         om.attrs = attrs;
157         om.vis = vis;
158         om.stab = self.stability(id);
159         om.id = id;
160         for i in &m.items {
161             self.visit_item(&**i, None, &mut om);
162         }
163         om
164     }
165
166     fn visit_view_path(&mut self, path: hir::ViewPath_,
167                        om: &mut Module,
168                        id: ast::NodeId,
169                        please_inline: bool) -> Option<hir::ViewPath_> {
170         match path {
171             hir::ViewPathSimple(dst, base) => {
172                 if self.resolve_id(id, Some(dst), false, om, please_inline) {
173                     None
174                 } else {
175                     Some(hir::ViewPathSimple(dst, base))
176                 }
177             }
178             hir::ViewPathList(p, paths) => {
179                 let mine = paths.into_iter().filter(|path| {
180                     !self.resolve_id(path.node.id(), None, false, om,
181                                      please_inline)
182                 }).collect::<Vec<hir::PathListItem>>();
183
184                 if mine.is_empty() {
185                     None
186                 } else {
187                     Some(hir::ViewPathList(p, mine))
188                 }
189             }
190
191             // these are feature gated anyway
192             hir::ViewPathGlob(base) => {
193                 if self.resolve_id(id, None, true, om, please_inline) {
194                     None
195                 } else {
196                     Some(hir::ViewPathGlob(base))
197                 }
198             }
199         }
200
201     }
202
203     fn resolve_id(&mut self, id: ast::NodeId, renamed: Option<ast::Name>,
204                   glob: bool, om: &mut Module, please_inline: bool) -> bool {
205         let tcx = match self.cx.tcx_opt() {
206             Some(tcx) => tcx,
207             None => return false
208         };
209         let def = tcx.def_map.borrow()[&id].def_id();
210         let def_node_id = match tcx.map.as_local_node_id(def) {
211             Some(n) => n, None => return false
212         };
213         let analysis = match self.analysis {
214             Some(analysis) => analysis, None => return false
215         };
216         if !please_inline && analysis.public_items.contains(&def) {
217             return false
218         }
219         if !self.view_item_stack.insert(def_node_id) { return false }
220
221         let ret = match tcx.map.get(def_node_id) {
222             hir_map::NodeItem(it) => {
223                 if glob {
224                     let prev = mem::replace(&mut self.inlining_from_glob, true);
225                     match it.node {
226                         hir::ItemMod(ref m) => {
227                             for i in &m.items {
228                                 self.visit_item(&**i, None, om);
229                             }
230                         }
231                         hir::ItemEnum(..) => {}
232                         _ => { panic!("glob not mapped to a module or enum"); }
233                     }
234                     self.inlining_from_glob = prev;
235                 } else {
236                     self.visit_item(it, renamed, om);
237                 }
238                 true
239             }
240             _ => false,
241         };
242         self.view_item_stack.remove(&def_node_id);
243         return ret;
244     }
245
246     pub fn visit_item(&mut self, item: &hir::Item,
247                       renamed: Option<ast::Name>, om: &mut Module) {
248         debug!("Visiting item {:?}", item);
249         let name = renamed.unwrap_or(item.name);
250         match item.node {
251             hir::ItemExternCrate(ref p) => {
252                 let path = match *p {
253                     None => None,
254                     Some(x) => Some(x.to_string()),
255                 };
256                 om.extern_crates.push(ExternCrate {
257                     name: name,
258                     path: path,
259                     vis: item.vis,
260                     attrs: item.attrs.clone(),
261                     whence: item.span,
262                 })
263             }
264             hir::ItemUse(ref vpath) => {
265                 let node = vpath.node.clone();
266                 let node = if item.vis == hir::Public {
267                     let please_inline = item.attrs.iter().any(|item| {
268                         match item.meta_item_list() {
269                             Some(list) => {
270                                 list.iter().any(|i| &i.name()[..] == "inline")
271                             }
272                             None => false,
273                         }
274                     });
275                     match self.visit_view_path(node, om, item.id, please_inline) {
276                         None => return,
277                         Some(p) => p
278                     }
279                 } else {
280                     node
281                 };
282                 om.imports.push(Import {
283                     id: item.id,
284                     vis: item.vis,
285                     attrs: item.attrs.clone(),
286                     node: node,
287                     whence: item.span,
288                 });
289             }
290             hir::ItemMod(ref m) => {
291                 om.mods.push(self.visit_mod_contents(item.span,
292                                                      item.attrs.clone(),
293                                                      item.vis,
294                                                      item.id,
295                                                      m,
296                                                      Some(name)));
297             },
298             hir::ItemEnum(ref ed, ref gen) =>
299                 om.enums.push(self.visit_enum_def(item, name, ed, gen)),
300             hir::ItemStruct(ref sd, ref gen) =>
301                 om.structs.push(self.visit_variant_data(item, name, sd, gen)),
302             hir::ItemFn(ref fd, ref unsafety, constness, ref abi, ref gen, _) =>
303                 om.fns.push(self.visit_fn(item, name, &**fd, unsafety,
304                                           constness, abi, gen)),
305             hir::ItemTy(ref ty, ref gen) => {
306                 let t = Typedef {
307                     ty: ty.clone(),
308                     gen: gen.clone(),
309                     name: name,
310                     id: item.id,
311                     attrs: item.attrs.clone(),
312                     whence: item.span,
313                     vis: item.vis,
314                     stab: self.stability(item.id),
315                 };
316                 om.typedefs.push(t);
317             },
318             hir::ItemStatic(ref ty, ref mut_, ref exp) => {
319                 let s = Static {
320                     type_: ty.clone(),
321                     mutability: mut_.clone(),
322                     expr: exp.clone(),
323                     id: item.id,
324                     name: name,
325                     attrs: item.attrs.clone(),
326                     whence: item.span,
327                     vis: item.vis,
328                     stab: self.stability(item.id),
329                 };
330                 om.statics.push(s);
331             },
332             hir::ItemConst(ref ty, ref exp) => {
333                 let s = Constant {
334                     type_: ty.clone(),
335                     expr: exp.clone(),
336                     id: item.id,
337                     name: name,
338                     attrs: item.attrs.clone(),
339                     whence: item.span,
340                     vis: item.vis,
341                     stab: self.stability(item.id),
342                 };
343                 om.constants.push(s);
344             },
345             hir::ItemTrait(unsafety, ref gen, ref b, ref items) => {
346                 let t = Trait {
347                     unsafety: unsafety,
348                     name: name,
349                     items: items.clone(),
350                     generics: gen.clone(),
351                     bounds: b.iter().cloned().collect(),
352                     id: item.id,
353                     attrs: item.attrs.clone(),
354                     whence: item.span,
355                     vis: item.vis,
356                     stab: self.stability(item.id),
357                 };
358                 om.traits.push(t);
359             },
360             hir::ItemImpl(unsafety, polarity, ref gen, ref tr, ref ty, ref items) => {
361                 let i = Impl {
362                     unsafety: unsafety,
363                     polarity: polarity,
364                     generics: gen.clone(),
365                     trait_: tr.clone(),
366                     for_: ty.clone(),
367                     items: items.clone(),
368                     attrs: item.attrs.clone(),
369                     id: item.id,
370                     whence: item.span,
371                     vis: item.vis,
372                     stab: self.stability(item.id),
373                 };
374                 // Don't duplicate impls when inlining glob imports, we'll pick
375                 // them up regardless of where they're located.
376                 if !self.inlining_from_glob {
377                     om.impls.push(i);
378                 }
379             },
380             hir::ItemDefaultImpl(unsafety, ref trait_ref) => {
381                 let i = DefaultImpl {
382                     unsafety: unsafety,
383                     trait_: trait_ref.clone(),
384                     id: item.id,
385                     attrs: item.attrs.clone(),
386                     whence: item.span,
387                 };
388                 // see comment above about ItemImpl
389                 if !self.inlining_from_glob {
390                     om.def_traits.push(i);
391                 }
392             }
393             hir::ItemForeignMod(ref fm) => {
394                 om.foreigns.push(fm.clone());
395             }
396         }
397     }
398
399     // convert each exported_macro into a doc item
400     fn visit_macro(&self, def: &hir::MacroDef) -> Macro {
401         Macro {
402             id: def.id,
403             attrs: def.attrs.clone(),
404             name: def.name,
405             whence: def.span,
406             stab: self.stability(def.id),
407             imported_from: def.imported_from,
408         }
409     }
410 }