]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/visit_ast.rs
introduce Guard enum
[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::ast;
17 use syntax::attr;
18 use syntax::source_map::Spanned;
19 use syntax_pos::{self, Span};
20
21 use rustc::hir::map as hir_map;
22 use rustc::hir::def::Def;
23 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
24 use rustc::middle::privacy::AccessLevel;
25 use rustc::util::nodemap::{FxHashSet, FxHashMap};
26
27 use rustc::hir;
28
29 use core;
30 use clean::{self, AttributesExt, NestedAttributesExt, def_id_to_path};
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, 'rcx: 'a, 'cstore: 'rcx> {
42     pub module: Module,
43     pub attrs: hir::HirVec<ast::Attribute>,
44     pub cx: &'a core::DocContext<'a, 'tcx, 'rcx, 'cstore>,
45     view_item_stack: FxHashSet<ast::NodeId>,
46     inlining: bool,
47     /// Is the current module and all of its parents public?
48     inside_public_path: bool,
49     exact_paths: Option<FxHashMap<DefId, Vec<String>>>,
50 }
51
52 impl<'a, 'tcx, 'rcx, 'cstore> RustdocVisitor<'a, 'tcx, 'rcx, 'cstore> {
53     pub fn new(
54         cx: &'a core::DocContext<'a, 'tcx, 'rcx, 'cstore>
55     ) -> RustdocVisitor<'a, 'tcx, 'rcx, 'cstore> {
56         // If the root is re-exported, terminate all recursion.
57         let mut stack = FxHashSet();
58         stack.insert(ast::CRATE_NODE_ID);
59         RustdocVisitor {
60             module: Module::new(None),
61             attrs: hir::HirVec::new(),
62             cx,
63             view_item_stack: stack,
64             inlining: false,
65             inside_public_path: true,
66             exact_paths: Some(FxHashMap()),
67         }
68     }
69
70     fn store_path(&mut self, did: DefId) {
71         // We can't use the entry api, as that keeps the mutable borrow of self active
72         // when we try to use cx
73         let exact_paths = self.exact_paths.as_mut().unwrap();
74         if exact_paths.get(&did).is_none() {
75             let path = def_id_to_path(self.cx, did, self.cx.crate_name.clone());
76             exact_paths.insert(did, path);
77         }
78     }
79
80     fn stability(&self, id: ast::NodeId) -> Option<attr::Stability> {
81         self.cx.tcx.hir.opt_local_def_id(id)
82             .and_then(|def_id| self.cx.tcx.lookup_stability(def_id)).cloned()
83     }
84
85     fn deprecation(&self, id: ast::NodeId) -> Option<attr::Deprecation> {
86         self.cx.tcx.hir.opt_local_def_id(id)
87             .and_then(|def_id| self.cx.tcx.lookup_deprecation(def_id))
88     }
89
90     pub fn visit(&mut self, krate: &hir::Crate) {
91         self.attrs = krate.attrs.clone();
92
93         self.module = self.visit_mod_contents(krate.span,
94                                               krate.attrs.clone(),
95                                               Spanned { span: syntax_pos::DUMMY_SP,
96                                                         node: hir::VisibilityKind::Public },
97                                               ast::CRATE_NODE_ID,
98                                               &krate.module,
99                                               None);
100         // attach the crate's exported macros to the top-level module:
101         let macro_exports: Vec<_> =
102             krate.exported_macros.iter().map(|def| self.visit_local_macro(def)).collect();
103         self.module.macros.extend(macro_exports);
104         self.module.is_crate = true;
105
106         self.cx.renderinfo.borrow_mut().exact_paths = self.exact_paths.take().unwrap();
107     }
108
109     pub fn visit_variant_data(&mut self, item: &hir::Item,
110                               name: ast::Name, sd: &hir::VariantData,
111                               generics: &hir::Generics) -> Struct {
112         debug!("Visiting struct");
113         let struct_type = struct_type_from_def(&*sd);
114         Struct {
115             id: item.id,
116             struct_type,
117             name,
118             vis: item.vis.clone(),
119             stab: self.stability(item.id),
120             depr: self.deprecation(item.id),
121             attrs: item.attrs.clone(),
122             generics: generics.clone(),
123             fields: sd.fields().iter().cloned().collect(),
124             whence: item.span
125         }
126     }
127
128     pub fn visit_union_data(&mut self, item: &hir::Item,
129                             name: ast::Name, sd: &hir::VariantData,
130                             generics: &hir::Generics) -> Union {
131         debug!("Visiting union");
132         let struct_type = struct_type_from_def(&*sd);
133         Union {
134             id: item.id,
135             struct_type,
136             name,
137             vis: item.vis.clone(),
138             stab: self.stability(item.id),
139             depr: self.deprecation(item.id),
140             attrs: item.attrs.clone(),
141             generics: generics.clone(),
142             fields: sd.fields().iter().cloned().collect(),
143             whence: item.span
144         }
145     }
146
147     pub fn visit_enum_def(&mut self, it: &hir::Item,
148                           name: ast::Name, def: &hir::EnumDef,
149                           params: &hir::Generics) -> Enum {
150         debug!("Visiting enum");
151         Enum {
152             name,
153             variants: def.variants.iter().map(|v| Variant {
154                 name: v.node.name,
155                 attrs: v.node.attrs.clone(),
156                 stab: self.stability(v.node.data.id()),
157                 depr: self.deprecation(v.node.data.id()),
158                 def: v.node.data.clone(),
159                 whence: v.span,
160             }).collect(),
161             vis: it.vis.clone(),
162             stab: self.stability(it.id),
163             depr: self.deprecation(it.id),
164             generics: params.clone(),
165             attrs: it.attrs.clone(),
166             id: it.id,
167             whence: it.span,
168         }
169     }
170
171     pub fn visit_fn(&mut self, item: &hir::Item,
172                     name: ast::Name, fd: &hir::FnDecl,
173                     header: hir::FnHeader,
174                     gen: &hir::Generics,
175                     body: hir::BodyId) -> Function {
176         debug!("Visiting fn");
177         Function {
178             id: item.id,
179             vis: item.vis.clone(),
180             stab: self.stability(item.id),
181             depr: self.deprecation(item.id),
182             attrs: item.attrs.clone(),
183             decl: fd.clone(),
184             name,
185             whence: item.span,
186             generics: gen.clone(),
187             header,
188             body,
189         }
190     }
191
192     pub fn visit_mod_contents(&mut self, span: Span, attrs: hir::HirVec<ast::Attribute>,
193                               vis: hir::Visibility, id: ast::NodeId,
194                               m: &hir::Mod,
195                               name: Option<ast::Name>) -> Module {
196         let mut om = Module::new(name);
197         om.where_outer = span;
198         om.where_inner = m.inner;
199         om.attrs = attrs;
200         om.vis = vis.clone();
201         om.stab = self.stability(id);
202         om.depr = self.deprecation(id);
203         om.id = id;
204         // Keep track of if there were any private modules in the path.
205         let orig_inside_public_path = self.inside_public_path;
206         self.inside_public_path &= vis.node.is_pub();
207         for i in &m.item_ids {
208             let item = self.cx.tcx.hir.expect_item(i.id);
209             self.visit_item(item, None, &mut om);
210         }
211         self.inside_public_path = orig_inside_public_path;
212         om
213     }
214
215     /// Tries to resolve the target of a `pub use` statement and inlines the
216     /// target if it is defined locally and would not be documented otherwise,
217     /// or when it is specifically requested with `please_inline`.
218     /// (the latter is the case when the import is marked `doc(inline)`)
219     ///
220     /// Cross-crate inlining occurs later on during crate cleaning
221     /// and follows different rules.
222     ///
223     /// Returns true if the target has been inlined.
224     fn maybe_inline_local(&mut self,
225                           id: ast::NodeId,
226                           def: Def,
227                           renamed: Option<ast::Name>,
228                           glob: bool,
229                           om: &mut Module,
230                           please_inline: bool) -> bool {
231
232         fn inherits_doc_hidden(cx: &core::DocContext, mut node: ast::NodeId) -> bool {
233             while let Some(id) = cx.tcx.hir.get_enclosing_scope(node) {
234                 node = id;
235                 if cx.tcx.hir.attrs(node).lists("doc").has_word("hidden") {
236                     return true;
237                 }
238                 if node == ast::CRATE_NODE_ID {
239                     break;
240                 }
241             }
242             false
243         }
244
245         debug!("maybe_inline_local def: {:?}", def);
246
247         let tcx = self.cx.tcx;
248         if def == Def::Err {
249             return false;
250         }
251         let def_did = def.def_id();
252
253         let use_attrs = tcx.hir.attrs(id);
254         // Don't inline doc(hidden) imports so they can be stripped at a later stage.
255         let is_no_inline = use_attrs.lists("doc").has_word("no_inline") ||
256                            use_attrs.lists("doc").has_word("hidden");
257
258         // For cross-crate impl inlining we need to know whether items are
259         // reachable in documentation - a previously nonreachable item can be
260         // made reachable by cross-crate inlining which we're checking here.
261         // (this is done here because we need to know this upfront)
262         if !def_did.is_local() && !is_no_inline {
263             let attrs = clean::inline::load_attrs(self.cx, def_did);
264             let self_is_hidden = attrs.lists("doc").has_word("hidden");
265             match def {
266                 Def::Trait(did) |
267                 Def::Struct(did) |
268                 Def::Union(did) |
269                 Def::Enum(did) |
270                 Def::TyForeign(did) |
271                 Def::TyAlias(did) if !self_is_hidden => {
272                     self.cx.access_levels.borrow_mut().map.insert(did, AccessLevel::Public);
273                 },
274                 Def::Mod(did) => if !self_is_hidden {
275                     ::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did);
276                 },
277                 _ => {},
278             }
279
280             return false
281         }
282
283         let def_node_id = match tcx.hir.as_local_node_id(def_did) {
284             Some(n) => n, None => return false
285         };
286
287         let is_private = !self.cx.access_levels.borrow().is_public(def_did);
288         let is_hidden = inherits_doc_hidden(self.cx, def_node_id);
289
290         // Only inline if requested or if the item would otherwise be stripped
291         if (!please_inline && !is_private && !is_hidden) || is_no_inline {
292             return false
293         }
294
295         if !self.view_item_stack.insert(def_node_id) { return false }
296
297         let ret = match tcx.hir.get(def_node_id) {
298             hir_map::NodeItem(&hir::Item { node: hir::ItemKind::Mod(ref m), .. }) if glob => {
299                 let prev = mem::replace(&mut self.inlining, true);
300                 for i in &m.item_ids {
301                     let i = self.cx.tcx.hir.expect_item(i.id);
302                     self.visit_item(i, None, om);
303                 }
304                 self.inlining = prev;
305                 true
306             }
307             hir_map::NodeItem(it) if !glob => {
308                 let prev = mem::replace(&mut self.inlining, true);
309                 self.visit_item(it, renamed, om);
310                 self.inlining = prev;
311                 true
312             }
313             hir_map::NodeForeignItem(it) if !glob => {
314                 // generate a fresh `extern {}` block if we want to inline a foreign item.
315                 om.foreigns.push(hir::ForeignMod {
316                     abi: tcx.hir.get_foreign_abi(it.id),
317                     items: vec![hir::ForeignItem {
318                         name: renamed.unwrap_or(it.name),
319                         .. it.clone()
320                     }].into(),
321                 });
322                 true
323             }
324             _ => false,
325         };
326         self.view_item_stack.remove(&def_node_id);
327         ret
328     }
329
330     pub fn visit_item(&mut self, item: &hir::Item,
331                       renamed: Option<ast::Name>, om: &mut Module) {
332         debug!("Visiting item {:?}", item);
333         let name = renamed.unwrap_or(item.name);
334
335         if item.vis.node.is_pub() {
336             let def_id = self.cx.tcx.hir.local_def_id(item.id);
337             self.store_path(def_id);
338         }
339
340         match item.node {
341             hir::ItemKind::ForeignMod(ref fm) => {
342                 // If inlining we only want to include public functions.
343                 om.foreigns.push(if self.inlining {
344                     hir::ForeignMod {
345                         abi: fm.abi,
346                         items: fm.items.iter().filter(|i| i.vis.node.is_pub()).cloned().collect(),
347                     }
348                 } else {
349                     fm.clone()
350                 });
351             }
352             // If we're inlining, skip private items.
353             _ if self.inlining && !item.vis.node.is_pub() => {}
354             hir::ItemKind::GlobalAsm(..) => {}
355             hir::ItemKind::ExternCrate(orig_name) => {
356                 let def_id = self.cx.tcx.hir.local_def_id(item.id);
357                 om.extern_crates.push(ExternCrate {
358                     cnum: self.cx.tcx.extern_mod_stmt_cnum(def_id)
359                                 .unwrap_or(LOCAL_CRATE),
360                     name,
361                     path: orig_name.map(|x|x.to_string()),
362                     vis: item.vis.clone(),
363                     attrs: item.attrs.clone(),
364                     whence: item.span,
365                 })
366             }
367             hir::ItemKind::Use(_, hir::UseKind::ListStem) => {}
368             hir::ItemKind::Use(ref path, kind) => {
369                 let is_glob = kind == hir::UseKind::Glob;
370
371                 // struct and variant constructors always show up alongside their definitions, we've
372                 // already processed them so just discard these.
373                 match path.def {
374                     Def::StructCtor(..) | Def::VariantCtor(..) => return,
375                     _ => {}
376                 }
377
378                 // If there was a private module in the current path then don't bother inlining
379                 // anything as it will probably be stripped anyway.
380                 if item.vis.node.is_pub() && self.inside_public_path {
381                     let please_inline = item.attrs.iter().any(|item| {
382                         match item.meta_item_list() {
383                             Some(ref list) if item.check_name("doc") => {
384                                 list.iter().any(|i| i.check_name("inline"))
385                             }
386                             _ => false,
387                         }
388                     });
389                     let name = if is_glob { None } else { Some(name) };
390                     if self.maybe_inline_local(item.id,
391                                                path.def,
392                                                name,
393                                                is_glob,
394                                                om,
395                                                please_inline) {
396                         return;
397                     }
398                 }
399
400                 om.imports.push(Import {
401                     name,
402                     id: item.id,
403                     vis: item.vis.clone(),
404                     attrs: item.attrs.clone(),
405                     path: (**path).clone(),
406                     glob: is_glob,
407                     whence: item.span,
408                 });
409             }
410             hir::ItemKind::Mod(ref m) => {
411                 om.mods.push(self.visit_mod_contents(item.span,
412                                                      item.attrs.clone(),
413                                                      item.vis.clone(),
414                                                      item.id,
415                                                      m,
416                                                      Some(name)));
417             },
418             hir::ItemKind::Enum(ref ed, ref gen) =>
419                 om.enums.push(self.visit_enum_def(item, name, ed, gen)),
420             hir::ItemKind::Struct(ref sd, ref gen) =>
421                 om.structs.push(self.visit_variant_data(item, name, sd, gen)),
422             hir::ItemKind::Union(ref sd, ref gen) =>
423                 om.unions.push(self.visit_union_data(item, name, sd, gen)),
424             hir::ItemKind::Fn(ref fd, header, ref gen, body) =>
425                 om.fns.push(self.visit_fn(item, name, &**fd, header, gen, body)),
426             hir::ItemKind::Ty(ref ty, ref gen) => {
427                 let t = Typedef {
428                     ty: ty.clone(),
429                     gen: gen.clone(),
430                     name,
431                     id: item.id,
432                     attrs: item.attrs.clone(),
433                     whence: item.span,
434                     vis: item.vis.clone(),
435                     stab: self.stability(item.id),
436                     depr: self.deprecation(item.id),
437                 };
438                 om.typedefs.push(t);
439             },
440             hir::ItemKind::Existential(ref exist_ty) => {
441                 let t = Existential {
442                     exist_ty: exist_ty.clone(),
443                     name,
444                     id: item.id,
445                     attrs: item.attrs.clone(),
446                     whence: item.span,
447                     vis: item.vis.clone(),
448                     stab: self.stability(item.id),
449                     depr: self.deprecation(item.id),
450                 };
451                 om.existentials.push(t);
452             },
453             hir::ItemKind::Static(ref ty, ref mut_, ref exp) => {
454                 let s = Static {
455                     type_: ty.clone(),
456                     mutability: mut_.clone(),
457                     expr: exp.clone(),
458                     id: item.id,
459                     name,
460                     attrs: item.attrs.clone(),
461                     whence: item.span,
462                     vis: item.vis.clone(),
463                     stab: self.stability(item.id),
464                     depr: self.deprecation(item.id),
465                 };
466                 om.statics.push(s);
467             },
468             hir::ItemKind::Const(ref ty, ref exp) => {
469                 let s = Constant {
470                     type_: ty.clone(),
471                     expr: exp.clone(),
472                     id: item.id,
473                     name,
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.constants.push(s);
481             },
482             hir::ItemKind::Trait(is_auto, unsafety, ref gen, ref b, ref item_ids) => {
483                 let items = item_ids.iter()
484                                     .map(|ti| self.cx.tcx.hir.trait_item(ti.id).clone())
485                                     .collect();
486                 let t = Trait {
487                     is_auto,
488                     unsafety,
489                     name,
490                     items,
491                     generics: gen.clone(),
492                     bounds: b.iter().cloned().collect(),
493                     id: item.id,
494                     attrs: item.attrs.clone(),
495                     whence: item.span,
496                     vis: item.vis.clone(),
497                     stab: self.stability(item.id),
498                     depr: self.deprecation(item.id),
499                 };
500                 om.traits.push(t);
501             },
502             hir::ItemKind::TraitAlias(..) => {
503                 unimplemented!("trait objects are not yet implemented")
504             },
505
506             hir::ItemKind::Impl(unsafety,
507                           polarity,
508                           defaultness,
509                           ref gen,
510                           ref tr,
511                           ref ty,
512                           ref item_ids) => {
513                 // Don't duplicate impls when inlining, we'll pick them up
514                 // regardless of where they're located.
515                 if !self.inlining {
516                     let items = item_ids.iter()
517                                         .map(|ii| self.cx.tcx.hir.impl_item(ii.id).clone())
518                                         .collect();
519                     let i = Impl {
520                         unsafety,
521                         polarity,
522                         defaultness,
523                         generics: gen.clone(),
524                         trait_: tr.clone(),
525                         for_: ty.clone(),
526                         items,
527                         attrs: item.attrs.clone(),
528                         id: item.id,
529                         whence: item.span,
530                         vis: item.vis.clone(),
531                         stab: self.stability(item.id),
532                         depr: self.deprecation(item.id),
533                     };
534                     om.impls.push(i);
535                 }
536             },
537         }
538     }
539
540     // convert each exported_macro into a doc item
541     fn visit_local_macro(&self, def: &hir::MacroDef) -> Macro {
542         debug!("visit_local_macro: {}", def.name);
543         let tts = def.body.trees().collect::<Vec<_>>();
544         // Extract the spans of all matchers. They represent the "interface" of the macro.
545         let matchers = tts.chunks(4).map(|arm| arm[0].span()).collect();
546
547         Macro {
548             def_id: self.cx.tcx.hir.local_def_id(def.id),
549             attrs: def.attrs.clone(),
550             name: def.name,
551             whence: def.span,
552             matchers,
553             stab: self.stability(def.id),
554             depr: self.deprecation(def.id),
555             imported_from: None,
556         }
557     }
558 }