]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/visit_ast.rs
Auto merge of #28938 - GlenDC:master, r=Manishearth
[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_struct_def(&mut self, item: &hir::Item,
88                             name: ast::Name, sd: &hir::StructDef,
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.clone(),
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.id),
115                 id: v.node.id,
116                 kind: v.node.kind.clone(),
117                 whence: v.span,
118             }).collect(),
119             vis: it.vis,
120             stab: self.stability(it.id),
121             generics: params.clone(),
122             attrs: it.attrs.clone(),
123             id: it.id,
124             whence: it.span,
125         }
126     }
127
128     pub fn visit_fn(&mut self, item: &hir::Item,
129                     name: ast::Name, fd: &hir::FnDecl,
130                     unsafety: &hir::Unsafety,
131                     constness: hir::Constness,
132                     abi: &abi::Abi,
133                     gen: &hir::Generics) -> Function {
134         debug!("Visiting fn");
135         Function {
136             id: item.id,
137             vis: item.vis,
138             stab: self.stability(item.id),
139             attrs: item.attrs.clone(),
140             decl: fd.clone(),
141             name: name,
142             whence: item.span,
143             generics: gen.clone(),
144             unsafety: *unsafety,
145             constness: constness,
146             abi: *abi,
147         }
148     }
149
150     pub fn visit_mod_contents(&mut self, span: Span, attrs: Vec<ast::Attribute> ,
151                               vis: hir::Visibility, id: ast::NodeId,
152                               m: &hir::Mod,
153                               name: Option<ast::Name>) -> Module {
154         let mut om = Module::new(name);
155         om.where_outer = span;
156         om.where_inner = m.inner;
157         om.attrs = attrs;
158         om.vis = vis;
159         om.stab = self.stability(id);
160         om.id = id;
161         for i in &m.items {
162             self.visit_item(&**i, None, &mut om);
163         }
164         om
165     }
166
167     fn visit_view_path(&mut self, path: hir::ViewPath_,
168                        om: &mut Module,
169                        id: ast::NodeId,
170                        please_inline: bool) -> Option<hir::ViewPath_> {
171         match path {
172             hir::ViewPathSimple(dst, base) => {
173                 if self.resolve_id(id, Some(dst), false, om, please_inline) {
174                     None
175                 } else {
176                     Some(hir::ViewPathSimple(dst, base))
177                 }
178             }
179             hir::ViewPathList(p, paths) => {
180                 let mine = paths.into_iter().filter(|path| {
181                     !self.resolve_id(path.node.id(), None, false, om,
182                                      please_inline)
183                 }).collect::<Vec<hir::PathListItem>>();
184
185                 if mine.is_empty() {
186                     None
187                 } else {
188                     Some(hir::ViewPathList(p, mine))
189                 }
190             }
191
192             // these are feature gated anyway
193             hir::ViewPathGlob(base) => {
194                 if self.resolve_id(id, None, true, om, please_inline) {
195                     None
196                 } else {
197                     Some(hir::ViewPathGlob(base))
198                 }
199             }
200         }
201
202     }
203
204     fn resolve_id(&mut self, id: ast::NodeId, renamed: Option<ast::Name>,
205                   glob: bool, om: &mut Module, please_inline: bool) -> bool {
206         let tcx = match self.cx.tcx_opt() {
207             Some(tcx) => tcx,
208             None => return false
209         };
210         let def = tcx.def_map.borrow()[&id].def_id();
211         let def_node_id = match tcx.map.as_local_node_id(def) {
212             Some(n) => n, None => return false
213         };
214         let analysis = match self.analysis {
215             Some(analysis) => analysis, None => return false
216         };
217         if !please_inline && analysis.public_items.contains(&def) {
218             return false
219         }
220         if !self.view_item_stack.insert(def_node_id) { return false }
221
222         let ret = match tcx.map.get(def_node_id) {
223             hir_map::NodeItem(it) => {
224                 if glob {
225                     let prev = mem::replace(&mut self.inlining_from_glob, true);
226                     match it.node {
227                         hir::ItemMod(ref m) => {
228                             for i in &m.items {
229                                 self.visit_item(&**i, None, om);
230                             }
231                         }
232                         hir::ItemEnum(..) => {}
233                         _ => { panic!("glob not mapped to a module or enum"); }
234                     }
235                     self.inlining_from_glob = prev;
236                 } else {
237                     self.visit_item(it, renamed, om);
238                 }
239                 true
240             }
241             _ => false,
242         };
243         self.view_item_stack.remove(&def_node_id);
244         return ret;
245     }
246
247     pub fn visit_item(&mut self, item: &hir::Item,
248                       renamed: Option<ast::Name>, om: &mut Module) {
249         debug!("Visiting item {:?}", item);
250         let name = renamed.unwrap_or(item.name);
251         match item.node {
252             hir::ItemExternCrate(ref p) => {
253                 let path = match *p {
254                     None => None,
255                     Some(x) => Some(x.to_string()),
256                 };
257                 om.extern_crates.push(ExternCrate {
258                     name: name,
259                     path: path,
260                     vis: item.vis,
261                     attrs: item.attrs.clone(),
262                     whence: item.span,
263                 })
264             }
265             hir::ItemUse(ref vpath) => {
266                 let node = vpath.node.clone();
267                 let node = if item.vis == hir::Public {
268                     let please_inline = item.attrs.iter().any(|item| {
269                         match item.meta_item_list() {
270                             Some(list) => {
271                                 list.iter().any(|i| &i.name()[..] == "inline")
272                             }
273                             None => false,
274                         }
275                     });
276                     match self.visit_view_path(node, om, item.id, please_inline) {
277                         None => return,
278                         Some(p) => p
279                     }
280                 } else {
281                     node
282                 };
283                 om.imports.push(Import {
284                     id: item.id,
285                     vis: item.vis,
286                     attrs: item.attrs.clone(),
287                     node: node,
288                     whence: item.span,
289                 });
290             }
291             hir::ItemMod(ref m) => {
292                 om.mods.push(self.visit_mod_contents(item.span,
293                                                      item.attrs.clone(),
294                                                      item.vis,
295                                                      item.id,
296                                                      m,
297                                                      Some(name)));
298             },
299             hir::ItemEnum(ref ed, ref gen) =>
300                 om.enums.push(self.visit_enum_def(item, name, ed, gen)),
301             hir::ItemStruct(ref sd, ref gen) =>
302                 om.structs.push(self.visit_struct_def(item, name, &**sd, gen)),
303             hir::ItemFn(ref fd, ref unsafety, constness, ref abi, ref gen, _) =>
304                 om.fns.push(self.visit_fn(item, name, &**fd, unsafety,
305                                           constness, abi, gen)),
306             hir::ItemTy(ref ty, ref gen) => {
307                 let t = Typedef {
308                     ty: ty.clone(),
309                     gen: gen.clone(),
310                     name: name,
311                     id: item.id,
312                     attrs: item.attrs.clone(),
313                     whence: item.span,
314                     vis: item.vis,
315                     stab: self.stability(item.id),
316                 };
317                 om.typedefs.push(t);
318             },
319             hir::ItemStatic(ref ty, ref mut_, ref exp) => {
320                 let s = Static {
321                     type_: ty.clone(),
322                     mutability: mut_.clone(),
323                     expr: exp.clone(),
324                     id: item.id,
325                     name: name,
326                     attrs: item.attrs.clone(),
327                     whence: item.span,
328                     vis: item.vis,
329                     stab: self.stability(item.id),
330                 };
331                 om.statics.push(s);
332             },
333             hir::ItemConst(ref ty, ref exp) => {
334                 let s = Constant {
335                     type_: ty.clone(),
336                     expr: exp.clone(),
337                     id: item.id,
338                     name: name,
339                     attrs: item.attrs.clone(),
340                     whence: item.span,
341                     vis: item.vis,
342                     stab: self.stability(item.id),
343                 };
344                 om.constants.push(s);
345             },
346             hir::ItemTrait(unsafety, ref gen, ref b, ref items) => {
347                 let t = Trait {
348                     unsafety: unsafety,
349                     name: name,
350                     items: items.clone(),
351                     generics: gen.clone(),
352                     bounds: b.iter().cloned().collect(),
353                     id: item.id,
354                     attrs: item.attrs.clone(),
355                     whence: item.span,
356                     vis: item.vis,
357                     stab: self.stability(item.id),
358                 };
359                 om.traits.push(t);
360             },
361             hir::ItemImpl(unsafety, polarity, ref gen, ref tr, ref ty, ref items) => {
362                 let i = Impl {
363                     unsafety: unsafety,
364                     polarity: polarity,
365                     generics: gen.clone(),
366                     trait_: tr.clone(),
367                     for_: ty.clone(),
368                     items: items.clone(),
369                     attrs: item.attrs.clone(),
370                     id: item.id,
371                     whence: item.span,
372                     vis: item.vis,
373                     stab: self.stability(item.id),
374                 };
375                 // Don't duplicate impls when inlining glob imports, we'll pick
376                 // them up regardless of where they're located.
377                 if !self.inlining_from_glob {
378                     om.impls.push(i);
379                 }
380             },
381             hir::ItemDefaultImpl(unsafety, ref trait_ref) => {
382                 let i = DefaultImpl {
383                     unsafety: unsafety,
384                     trait_: trait_ref.clone(),
385                     id: item.id,
386                     attrs: item.attrs.clone(),
387                     whence: item.span,
388                 };
389                 // see comment above about ItemImpl
390                 if !self.inlining_from_glob {
391                     om.def_traits.push(i);
392                 }
393             }
394             hir::ItemForeignMod(ref fm) => {
395                 om.foreigns.push(fm.clone());
396             }
397         }
398     }
399
400     // convert each exported_macro into a doc item
401     fn visit_macro(&self, def: &hir::MacroDef) -> Macro {
402         Macro {
403             id: def.id,
404             attrs: def.attrs.clone(),
405             name: def.name,
406             whence: def.span,
407             stab: self.stability(def.id),
408             imported_from: def.imported_from,
409         }
410     }
411 }