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