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