]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/visit_ast.rs
0334c5ef5c4f4397120d1408d1f8aa6227c8e5f8
[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_pos::Span;
22
23 use rustc::hir::map as hir_map;
24 use rustc::hir::def::Def;
25 use rustc::middle::privacy::AccessLevel;
26
27 use rustc::hir;
28
29 use core;
30 use clean::{self, Clean, Attributes};
31 use doctree::*;
32
33 // looks to me like the first two of these are actually
34 // output parameters, maybe only mutated once; perhaps
35 // better simply to have the visit method return a tuple
36 // containing them?
37
38 // also, is there some reason that this doesn't use the 'visit'
39 // framework from syntax?
40
41 pub struct RustdocVisitor<'a, 'tcx: 'a> {
42     pub module: Module,
43     pub attrs: hir::HirVec<ast::Attribute>,
44     pub cx: &'a core::DocContext<'a, 'tcx>,
45     view_item_stack: HashSet<ast::NodeId>,
46     inlining_from_glob: bool,
47 }
48
49 impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
50     pub fn new(cx: &'a core::DocContext<'a, 'tcx>) -> 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             view_item_stack: stack,
59             inlining_from_glob: false,
60         }
61     }
62
63     fn stability(&self, id: ast::NodeId) -> Option<attr::Stability> {
64         self.cx.tcx_opt().and_then(|tcx| {
65             self.cx.map.opt_local_def_id(id)
66                        .and_then(|def_id| tcx.lookup_stability(def_id))
67                        .cloned()
68         })
69     }
70
71     fn deprecation(&self, id: ast::NodeId) -> Option<attr::Deprecation> {
72         self.cx.tcx_opt().and_then(|tcx| {
73             self.cx.map.opt_local_def_id(id)
74                        .and_then(|def_id| tcx.lookup_deprecation(def_id))
75         })
76     }
77
78     pub fn visit(&mut self, krate: &hir::Crate) {
79         self.attrs = krate.attrs.clone();
80
81         self.module = self.visit_mod_contents(krate.span,
82                                               krate.attrs.clone(),
83                                               hir::Public,
84                                               ast::CRATE_NODE_ID,
85                                               &krate.module,
86                                               None);
87         // attach the crate's exported macros to the top-level module:
88         self.module.macros = krate.exported_macros.iter()
89             .map(|def| self.visit_macro(def)).collect();
90         self.module.is_crate = true;
91     }
92
93     pub fn visit_variant_data(&mut self, item: &hir::Item,
94                             name: ast::Name, sd: &hir::VariantData,
95                             generics: &hir::Generics) -> Struct {
96         debug!("Visiting struct");
97         let struct_type = struct_type_from_def(&*sd);
98         Struct {
99             id: item.id,
100             struct_type: struct_type,
101             name: name,
102             vis: item.vis.clone(),
103             stab: self.stability(item.id),
104             depr: self.deprecation(item.id),
105             attrs: item.attrs.clone(),
106             generics: generics.clone(),
107             fields: sd.fields().iter().cloned().collect(),
108             whence: item.span
109         }
110     }
111
112     pub fn visit_enum_def(&mut self, it: &hir::Item,
113                           name: ast::Name, def: &hir::EnumDef,
114                           params: &hir::Generics) -> Enum {
115         debug!("Visiting enum");
116         Enum {
117             name: name,
118             variants: def.variants.iter().map(|v| Variant {
119                 name: v.node.name,
120                 attrs: v.node.attrs.clone(),
121                 stab: self.stability(v.node.data.id()),
122                 depr: self.deprecation(v.node.data.id()),
123                 def: v.node.data.clone(),
124                 whence: v.span,
125             }).collect(),
126             vis: it.vis.clone(),
127             stab: self.stability(it.id),
128             depr: self.deprecation(it.id),
129             generics: params.clone(),
130             attrs: it.attrs.clone(),
131             id: it.id,
132             whence: it.span,
133         }
134     }
135
136     pub fn visit_fn(&mut self, item: &hir::Item,
137                     name: ast::Name, fd: &hir::FnDecl,
138                     unsafety: &hir::Unsafety,
139                     constness: hir::Constness,
140                     abi: &abi::Abi,
141                     gen: &hir::Generics) -> Function {
142         debug!("Visiting fn");
143         Function {
144             id: item.id,
145             vis: item.vis.clone(),
146             stab: self.stability(item.id),
147             depr: self.deprecation(item.id),
148             attrs: item.attrs.clone(),
149             decl: fd.clone(),
150             name: name,
151             whence: item.span,
152             generics: gen.clone(),
153             unsafety: *unsafety,
154             constness: constness,
155             abi: *abi,
156         }
157     }
158
159     pub fn visit_mod_contents(&mut self, span: Span, attrs: hir::HirVec<ast::Attribute>,
160                               vis: hir::Visibility, id: ast::NodeId,
161                               m: &hir::Mod,
162                               name: Option<ast::Name>) -> Module {
163         let mut om = Module::new(name);
164         om.where_outer = span;
165         om.where_inner = m.inner;
166         om.attrs = attrs;
167         om.vis = vis.clone();
168         om.stab = self.stability(id);
169         om.depr = self.deprecation(id);
170         om.id = id;
171         for i in &m.item_ids {
172             let item = self.cx.map.expect_item(i.id);
173             self.visit_item(item, None, &mut om);
174         }
175         om
176     }
177
178     fn visit_view_path(&mut self, path: hir::ViewPath_,
179                        om: &mut Module,
180                        id: ast::NodeId,
181                        please_inline: bool) -> Option<hir::ViewPath_> {
182         match path {
183             hir::ViewPathSimple(dst, base) => {
184                 if self.maybe_inline_local(id, Some(dst), false, om, please_inline) {
185                     None
186                 } else {
187                     Some(hir::ViewPathSimple(dst, base))
188                 }
189             }
190             hir::ViewPathList(p, paths) => {
191                 let mine = paths.into_iter().filter(|path| {
192                     !self.maybe_inline_local(path.node.id(), path.node.rename(),
193                                              false, om, please_inline)
194                 }).collect::<hir::HirVec<hir::PathListItem>>();
195
196                 if mine.is_empty() {
197                     None
198                 } else {
199                     Some(hir::ViewPathList(p, mine))
200                 }
201             }
202
203             hir::ViewPathGlob(base) => {
204                 if self.maybe_inline_local(id, None, true, om, please_inline) {
205                     None
206                 } else {
207                     Some(hir::ViewPathGlob(base))
208                 }
209             }
210         }
211
212     }
213
214     /// Tries to resolve the target of a `pub use` statement and inlines the
215     /// target if it is defined locally and would not be documented otherwise,
216     /// or when it is specifically requested with `please_inline`.
217     /// (the latter is the case when the import is marked `doc(inline)`)
218     ///
219     /// Cross-crate inlining occurs later on during crate cleaning
220     /// and follows different rules.
221     ///
222     /// Returns true if the target has been inlined.
223     fn maybe_inline_local(&mut self, id: ast::NodeId, renamed: Option<ast::Name>,
224                   glob: bool, om: &mut Module, please_inline: bool) -> bool {
225
226         fn inherits_doc_hidden(cx: &core::DocContext, mut node: ast::NodeId) -> bool {
227             while let Some(id) = cx.map.get_enclosing_scope(node) {
228                 node = id;
229                 let attrs = cx.map.attrs(node).clean(cx);
230                 if attrs.list("doc").has_word("hidden") {
231                     return true;
232                 }
233                 if node == ast::CRATE_NODE_ID {
234                     break;
235                 }
236             }
237             false
238         }
239
240         let tcx = match self.cx.tcx_opt() {
241             Some(tcx) => tcx,
242             None => return false
243         };
244         let def = tcx.expect_def(id);
245         let def_did = def.def_id();
246
247         let use_attrs = tcx.map.attrs(id).clean(self.cx);
248         // Don't inline doc(hidden) imports so they can be stripped at a later stage.
249         let is_no_inline = use_attrs.list("doc").has_word("no_inline") ||
250                            use_attrs.list("doc").has_word("hidden");
251
252         // For cross-crate impl inlining we need to know whether items are
253         // reachable in documentation - a previously nonreachable item can be
254         // made reachable by cross-crate inlining which we're checking here.
255         // (this is done here because we need to know this upfront)
256         if !def_did.is_local() && !is_no_inline {
257             let attrs = clean::inline::load_attrs(self.cx, tcx, def_did);
258             let self_is_hidden = attrs.list("doc").has_word("hidden");
259             match def {
260                 Def::Trait(did) |
261                 Def::Struct(did) |
262                 Def::Enum(did) |
263                 Def::TyAlias(did) if !self_is_hidden => {
264                     self.cx.access_levels.borrow_mut().map.insert(did, AccessLevel::Public);
265                 },
266                 Def::Mod(did) => if !self_is_hidden {
267                     ::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did);
268                 },
269                 _ => {},
270             }
271             return false
272         }
273
274         let def_node_id = match tcx.map.as_local_node_id(def_did) {
275             Some(n) => n, None => return false
276         };
277
278         let is_private = !self.cx.access_levels.borrow().is_public(def_did);
279         let is_hidden = inherits_doc_hidden(self.cx, def_node_id);
280
281         // Only inline if requested or if the item would otherwise be stripped
282         if (!please_inline && !is_private && !is_hidden) || is_no_inline {
283             return false
284         }
285
286         if !self.view_item_stack.insert(def_node_id) { return false }
287
288         let ret = match tcx.map.get(def_node_id) {
289             hir_map::NodeItem(it) => {
290                 if glob {
291                     let prev = mem::replace(&mut self.inlining_from_glob, true);
292                     match it.node {
293                         hir::ItemMod(ref m) => {
294                             for i in &m.item_ids {
295                                 let i = self.cx.map.expect_item(i.id);
296                                 self.visit_item(i, None, om);
297                             }
298                         }
299                         hir::ItemEnum(..) => {}
300                         _ => { panic!("glob not mapped to a module or enum"); }
301                     }
302                     self.inlining_from_glob = prev;
303                 } else {
304                     self.visit_item(it, renamed, om);
305                 }
306                 true
307             }
308             _ => false,
309         };
310         self.view_item_stack.remove(&def_node_id);
311         return ret;
312     }
313
314     pub fn visit_item(&mut self, item: &hir::Item,
315                       renamed: Option<ast::Name>, om: &mut Module) {
316         debug!("Visiting item {:?}", item);
317         let name = renamed.unwrap_or(item.name);
318         match item.node {
319             hir::ItemExternCrate(ref p) => {
320                 let cstore = &self.cx.sess().cstore;
321                 om.extern_crates.push(ExternCrate {
322                     cnum: cstore.extern_mod_stmt_cnum(item.id)
323                                 .unwrap_or(ast::CrateNum::max_value()),
324                     name: name,
325                     path: p.map(|x|x.to_string()),
326                     vis: item.vis.clone(),
327                     attrs: item.attrs.clone(),
328                     whence: item.span,
329                 })
330             }
331             hir::ItemUse(ref vpath) => {
332                 let node = vpath.node.clone();
333                 let node = if item.vis == hir::Public {
334                     let please_inline = item.attrs.iter().any(|item| {
335                         match item.meta_item_list() {
336                             Some(list) if &item.name()[..] == "doc" => {
337                                 list.iter().any(|i| &i.name()[..] == "inline")
338                             }
339                             _ => false,
340                         }
341                     });
342                     match self.visit_view_path(node, om, item.id, please_inline) {
343                         None => return,
344                         Some(p) => p
345                     }
346                 } else {
347                     node
348                 };
349                 om.imports.push(Import {
350                     id: item.id,
351                     vis: item.vis.clone(),
352                     attrs: item.attrs.clone(),
353                     node: node,
354                     whence: item.span,
355                 });
356             }
357             hir::ItemMod(ref m) => {
358                 om.mods.push(self.visit_mod_contents(item.span,
359                                                      item.attrs.clone(),
360                                                      item.vis.clone(),
361                                                      item.id,
362                                                      m,
363                                                      Some(name)));
364             },
365             hir::ItemEnum(ref ed, ref gen) =>
366                 om.enums.push(self.visit_enum_def(item, name, ed, gen)),
367             hir::ItemStruct(ref sd, ref gen) =>
368                 om.structs.push(self.visit_variant_data(item, name, sd, gen)),
369             hir::ItemFn(ref fd, ref unsafety, constness, ref abi, ref gen, _) =>
370                 om.fns.push(self.visit_fn(item, name, &**fd, unsafety,
371                                           constness, abi, gen)),
372             hir::ItemTy(ref ty, ref gen) => {
373                 let t = Typedef {
374                     ty: ty.clone(),
375                     gen: gen.clone(),
376                     name: name,
377                     id: item.id,
378                     attrs: item.attrs.clone(),
379                     whence: item.span,
380                     vis: item.vis.clone(),
381                     stab: self.stability(item.id),
382                     depr: self.deprecation(item.id),
383                 };
384                 om.typedefs.push(t);
385             },
386             hir::ItemStatic(ref ty, ref mut_, ref exp) => {
387                 let s = Static {
388                     type_: ty.clone(),
389                     mutability: mut_.clone(),
390                     expr: exp.clone(),
391                     id: item.id,
392                     name: name,
393                     attrs: item.attrs.clone(),
394                     whence: item.span,
395                     vis: item.vis.clone(),
396                     stab: self.stability(item.id),
397                     depr: self.deprecation(item.id),
398                 };
399                 om.statics.push(s);
400             },
401             hir::ItemConst(ref ty, ref exp) => {
402                 let s = Constant {
403                     type_: ty.clone(),
404                     expr: exp.clone(),
405                     id: item.id,
406                     name: name,
407                     attrs: item.attrs.clone(),
408                     whence: item.span,
409                     vis: item.vis.clone(),
410                     stab: self.stability(item.id),
411                     depr: self.deprecation(item.id),
412                 };
413                 om.constants.push(s);
414             },
415             hir::ItemTrait(unsafety, ref gen, ref b, ref items) => {
416                 let t = Trait {
417                     unsafety: unsafety,
418                     name: name,
419                     items: items.clone(),
420                     generics: gen.clone(),
421                     bounds: b.iter().cloned().collect(),
422                     id: item.id,
423                     attrs: item.attrs.clone(),
424                     whence: item.span,
425                     vis: item.vis.clone(),
426                     stab: self.stability(item.id),
427                     depr: self.deprecation(item.id),
428                 };
429                 om.traits.push(t);
430             },
431             hir::ItemImpl(unsafety, polarity, ref gen, ref tr, ref ty, ref items) => {
432                 let i = Impl {
433                     unsafety: unsafety,
434                     polarity: polarity,
435                     generics: gen.clone(),
436                     trait_: tr.clone(),
437                     for_: ty.clone(),
438                     items: items.clone(),
439                     attrs: item.attrs.clone(),
440                     id: item.id,
441                     whence: item.span,
442                     vis: item.vis.clone(),
443                     stab: self.stability(item.id),
444                     depr: self.deprecation(item.id),
445                 };
446                 // Don't duplicate impls when inlining glob imports, we'll pick
447                 // them up regardless of where they're located.
448                 if !self.inlining_from_glob {
449                     om.impls.push(i);
450                 }
451             },
452             hir::ItemDefaultImpl(unsafety, ref trait_ref) => {
453                 let i = DefaultImpl {
454                     unsafety: unsafety,
455                     trait_: trait_ref.clone(),
456                     id: item.id,
457                     attrs: item.attrs.clone(),
458                     whence: item.span,
459                 };
460                 // see comment above about ItemImpl
461                 if !self.inlining_from_glob {
462                     om.def_traits.push(i);
463                 }
464             }
465             hir::ItemForeignMod(ref fm) => {
466                 om.foreigns.push(fm.clone());
467             }
468         }
469     }
470
471     // convert each exported_macro into a doc item
472     fn visit_macro(&self, def: &hir::MacroDef) -> Macro {
473         // Extract the spans of all matchers. They represent the "interface" of the macro.
474         let matchers = def.body.chunks(4).map(|arm| arm[0].get_span()).collect();
475
476         Macro {
477             id: def.id,
478             attrs: def.attrs.clone(),
479             name: def.name,
480             whence: def.span,
481             matchers: matchers,
482             stab: self.stability(def.id),
483             depr: self.deprecation(def.id),
484             imported_from: def.imported_from,
485         }
486     }
487 }