]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/visit_ast.rs
Rollup merge of #40521 - TimNN:panic-free-shift, 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::mem;
15
16 use syntax::abi;
17 use syntax::ast;
18 use syntax::attr;
19 use syntax::tokenstream::TokenStream;
20 use syntax_pos::Span;
21
22 use rustc::hir::map as hir_map;
23 use rustc::hir::def::Def;
24 use rustc::hir::def_id::LOCAL_CRATE;
25 use rustc::middle::cstore::LoadedMacro;
26 use rustc::middle::privacy::AccessLevel;
27 use rustc::util::nodemap::FxHashSet;
28
29 use rustc::hir;
30
31 use core;
32 use clean::{self, AttributesExt, NestedAttributesExt};
33 use doctree::*;
34
35 // looks to me like the first two of these are actually
36 // output parameters, maybe only mutated once; perhaps
37 // better simply to have the visit method return a tuple
38 // containing them?
39
40 // also, is there some reason that this doesn't use the 'visit'
41 // framework from syntax?
42
43 pub struct RustdocVisitor<'a, 'tcx: 'a> {
44     pub module: Module,
45     pub attrs: hir::HirVec<ast::Attribute>,
46     pub cx: &'a core::DocContext<'a, 'tcx>,
47     view_item_stack: FxHashSet<ast::NodeId>,
48     inlining: bool,
49     /// Is the current module and all of its parents public?
50     inside_public_path: bool,
51 }
52
53 impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
54     pub fn new(cx: &'a core::DocContext<'a, 'tcx>) -> RustdocVisitor<'a, 'tcx> {
55         // If the root is reexported, terminate all recursion.
56         let mut stack = FxHashSet();
57         stack.insert(ast::CRATE_NODE_ID);
58         RustdocVisitor {
59             module: Module::new(None),
60             attrs: hir::HirVec::new(),
61             cx: cx,
62             view_item_stack: stack,
63             inlining: false,
64             inside_public_path: true,
65         }
66     }
67
68     fn stability(&self, id: ast::NodeId) -> Option<attr::Stability> {
69         self.cx.tcx.hir.opt_local_def_id(id)
70             .and_then(|def_id| self.cx.tcx.lookup_stability(def_id)).cloned()
71     }
72
73     fn deprecation(&self, id: ast::NodeId) -> Option<attr::Deprecation> {
74         self.cx.tcx.hir.opt_local_def_id(id)
75             .and_then(|def_id| self.cx.tcx.lookup_deprecation(def_id))
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         let macro_exports: Vec<_> =
89             krate.exported_macros.iter().map(|def| self.visit_local_macro(def)).collect();
90         self.module.macros.extend(macro_exports);
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.clone(),
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_union_data(&mut self, item: &hir::Item,
114                             name: ast::Name, sd: &hir::VariantData,
115                             generics: &hir::Generics) -> Union {
116         debug!("Visiting union");
117         let struct_type = struct_type_from_def(&*sd);
118         Union {
119             id: item.id,
120             struct_type: struct_type,
121             name: name,
122             vis: item.vis.clone(),
123             stab: self.stability(item.id),
124             depr: self.deprecation(item.id),
125             attrs: item.attrs.clone(),
126             generics: generics.clone(),
127             fields: sd.fields().iter().cloned().collect(),
128             whence: item.span
129         }
130     }
131
132     pub fn visit_enum_def(&mut self, it: &hir::Item,
133                           name: ast::Name, def: &hir::EnumDef,
134                           params: &hir::Generics) -> Enum {
135         debug!("Visiting enum");
136         Enum {
137             name: name,
138             variants: def.variants.iter().map(|v| Variant {
139                 name: v.node.name,
140                 attrs: v.node.attrs.clone(),
141                 stab: self.stability(v.node.data.id()),
142                 depr: self.deprecation(v.node.data.id()),
143                 def: v.node.data.clone(),
144                 whence: v.span,
145             }).collect(),
146             vis: it.vis.clone(),
147             stab: self.stability(it.id),
148             depr: self.deprecation(it.id),
149             generics: params.clone(),
150             attrs: it.attrs.clone(),
151             id: it.id,
152             whence: it.span,
153         }
154     }
155
156     pub fn visit_fn(&mut self, item: &hir::Item,
157                     name: ast::Name, fd: &hir::FnDecl,
158                     unsafety: &hir::Unsafety,
159                     constness: hir::Constness,
160                     abi: &abi::Abi,
161                     gen: &hir::Generics,
162                     body: hir::BodyId) -> 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             body: body,
178         }
179     }
180
181     pub fn visit_mod_contents(&mut self, span: Span, attrs: hir::HirVec<ast::Attribute>,
182                               vis: hir::Visibility, id: ast::NodeId,
183                               m: &hir::Mod,
184                               name: Option<ast::Name>) -> Module {
185         let mut om = Module::new(name);
186         om.where_outer = span;
187         om.where_inner = m.inner;
188         om.attrs = attrs;
189         om.vis = vis.clone();
190         om.stab = self.stability(id);
191         om.depr = self.deprecation(id);
192         om.id = id;
193         // Keep track of if there were any private modules in the path.
194         let orig_inside_public_path = self.inside_public_path;
195         self.inside_public_path &= vis == hir::Public;
196         for i in &m.item_ids {
197             let item = self.cx.tcx.hir.expect_item(i.id);
198             self.visit_item(item, None, &mut om);
199         }
200         self.inside_public_path = orig_inside_public_path;
201         if let Some(exports) = self.cx.export_map.get(&id) {
202             for export in exports {
203                 if let Def::Macro(def_id, ..) = export.def {
204                     if def_id.krate == LOCAL_CRATE {
205                         continue // These are `krate.exported_macros`, handled in `self.visit()`.
206                     }
207                     let imported_from = self.cx.sess().cstore.original_crate_name(def_id.krate);
208                     let def = match self.cx.sess().cstore.load_macro(def_id, self.cx.sess()) {
209                         LoadedMacro::MacroDef(macro_def) => macro_def,
210                         // FIXME(jseyfried): document proc macro reexports
211                         LoadedMacro::ProcMacro(..) => continue,
212                     };
213
214                     let matchers = if let ast::ItemKind::MacroDef(ref tokens) = def.node {
215                         let tts: Vec<_> = TokenStream::from(tokens.clone()).into_trees().collect();
216                         tts.chunks(4).map(|arm| arm[0].span()).collect()
217                     } else {
218                         unreachable!()
219                     };
220                     om.macros.push(Macro {
221                         def_id: def_id,
222                         attrs: def.attrs.clone().into(),
223                         name: def.ident.name,
224                         whence: def.span,
225                         matchers: matchers,
226                         stab: self.stability(def.id),
227                         depr: self.deprecation(def.id),
228                         imported_from: Some(imported_from),
229                     })
230                 }
231             }
232         }
233         om
234     }
235
236     /// Tries to resolve the target of a `pub use` statement and inlines the
237     /// target if it is defined locally and would not be documented otherwise,
238     /// or when it is specifically requested with `please_inline`.
239     /// (the latter is the case when the import is marked `doc(inline)`)
240     ///
241     /// Cross-crate inlining occurs later on during crate cleaning
242     /// and follows different rules.
243     ///
244     /// Returns true if the target has been inlined.
245     fn maybe_inline_local(&mut self,
246                           id: ast::NodeId,
247                           def: Def,
248                           renamed: Option<ast::Name>,
249                           glob: bool,
250                           om: &mut Module,
251                           please_inline: bool) -> bool {
252
253         fn inherits_doc_hidden(cx: &core::DocContext, mut node: ast::NodeId) -> bool {
254             while let Some(id) = cx.tcx.hir.get_enclosing_scope(node) {
255                 node = id;
256                 if cx.tcx.hir.attrs(node).lists("doc").has_word("hidden") {
257                     return true;
258                 }
259                 if node == ast::CRATE_NODE_ID {
260                     break;
261                 }
262             }
263             false
264         }
265
266         let tcx = self.cx.tcx;
267         if def == Def::Err {
268             return false;
269         }
270         let def_did = def.def_id();
271
272         let use_attrs = tcx.hir.attrs(id);
273         // Don't inline doc(hidden) imports so they can be stripped at a later stage.
274         let is_no_inline = use_attrs.lists("doc").has_word("no_inline") ||
275                            use_attrs.lists("doc").has_word("hidden");
276
277         // For cross-crate impl inlining we need to know whether items are
278         // reachable in documentation - a previously nonreachable item can be
279         // made reachable by cross-crate inlining which we're checking here.
280         // (this is done here because we need to know this upfront)
281         if !def_did.is_local() && !is_no_inline {
282             let attrs = clean::inline::load_attrs(self.cx, def_did);
283             let self_is_hidden = attrs.lists("doc").has_word("hidden");
284             match def {
285                 Def::Trait(did) |
286                 Def::Struct(did) |
287                 Def::Union(did) |
288                 Def::Enum(did) |
289                 Def::TyAlias(did) if !self_is_hidden => {
290                     self.cx.access_levels.borrow_mut().map.insert(did, AccessLevel::Public);
291                 },
292                 Def::Mod(did) => if !self_is_hidden {
293                     ::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did);
294                 },
295                 _ => {},
296             }
297             return false
298         }
299
300         let def_node_id = match tcx.hir.as_local_node_id(def_did) {
301             Some(n) => n, None => return false
302         };
303
304         let is_private = !self.cx.access_levels.borrow().is_public(def_did);
305         let is_hidden = inherits_doc_hidden(self.cx, def_node_id);
306
307         // Only inline if requested or if the item would otherwise be stripped
308         if (!please_inline && !is_private && !is_hidden) || is_no_inline {
309             return false
310         }
311
312         if !self.view_item_stack.insert(def_node_id) { return false }
313
314         let ret = match tcx.hir.get(def_node_id) {
315             hir_map::NodeItem(it) => {
316                 let prev = mem::replace(&mut self.inlining, true);
317                 if glob {
318                     match it.node {
319                         hir::ItemMod(ref m) => {
320                             for i in &m.item_ids {
321                                 let i = self.cx.tcx.hir.expect_item(i.id);
322                                 self.visit_item(i, None, om);
323                             }
324                         }
325                         hir::ItemEnum(..) => {}
326                         _ => { panic!("glob not mapped to a module or enum"); }
327                     }
328                 } else {
329                     self.visit_item(it, renamed, om);
330                 }
331                 self.inlining = prev;
332                 true
333             }
334             _ => false,
335         };
336         self.view_item_stack.remove(&def_node_id);
337         ret
338     }
339
340     pub fn visit_item(&mut self, item: &hir::Item,
341                       renamed: Option<ast::Name>, om: &mut Module) {
342         debug!("Visiting item {:?}", item);
343         let name = renamed.unwrap_or(item.name);
344         match item.node {
345             hir::ItemForeignMod(ref fm) => {
346                 // If inlining we only want to include public functions.
347                 om.foreigns.push(if self.inlining {
348                     hir::ForeignMod {
349                         abi: fm.abi,
350                         items: fm.items.iter().filter(|i| i.vis == hir::Public).cloned().collect(),
351                     }
352                 } else {
353                     fm.clone()
354                 });
355             }
356             // If we're inlining, skip private items.
357             _ if self.inlining && item.vis != hir::Public => {}
358             hir::ItemExternCrate(ref p) => {
359                 let cstore = &self.cx.sess().cstore;
360                 om.extern_crates.push(ExternCrate {
361                     cnum: cstore.extern_mod_stmt_cnum(item.id)
362                                 .unwrap_or(LOCAL_CRATE),
363                     name: name,
364                     path: p.map(|x|x.to_string()),
365                     vis: item.vis.clone(),
366                     attrs: item.attrs.clone(),
367                     whence: item.span,
368                 })
369             }
370             hir::ItemUse(_, hir::UseKind::ListStem) => {}
371             hir::ItemUse(ref path, kind) => {
372                 let is_glob = kind == hir::UseKind::Glob;
373
374                 // If there was a private module in the current path then don't bother inlining
375                 // anything as it will probably be stripped anyway.
376                 if item.vis == hir::Public && self.inside_public_path {
377                     let please_inline = item.attrs.iter().any(|item| {
378                         match item.meta_item_list() {
379                             Some(ref list) if item.check_name("doc") => {
380                                 list.iter().any(|i| i.check_name("inline"))
381                             }
382                             _ => false,
383                         }
384                     });
385                     let name = if is_glob { None } else { Some(name) };
386                     if self.maybe_inline_local(item.id,
387                                                path.def,
388                                                name,
389                                                is_glob,
390                                                om,
391                                                please_inline) {
392                         return;
393                     }
394                 }
395
396                 om.imports.push(Import {
397                     name: name,
398                     id: item.id,
399                     vis: item.vis.clone(),
400                     attrs: item.attrs.clone(),
401                     path: (**path).clone(),
402                     glob: is_glob,
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, body) =>
421                 om.fns.push(self.visit_fn(item, name, &**fd, unsafety,
422                                           constness, abi, gen, body)),
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 item_ids) => {
467                 let items = item_ids.iter()
468                                     .map(|ti| self.cx.tcx.hir.trait_item(ti.id).clone())
469                                     .collect();
470                 let t = Trait {
471                     unsafety: unsafety,
472                     name: name,
473                     items: items,
474                     generics: gen.clone(),
475                     bounds: b.iter().cloned().collect(),
476                     id: item.id,
477                     attrs: item.attrs.clone(),
478                     whence: item.span,
479                     vis: item.vis.clone(),
480                     stab: self.stability(item.id),
481                     depr: self.deprecation(item.id),
482                 };
483                 om.traits.push(t);
484             },
485
486             hir::ItemImpl(unsafety, polarity, ref gen, ref tr, ref ty, ref item_ids) => {
487                 // Don't duplicate impls when inlining, we'll pick them up
488                 // regardless of where they're located.
489                 if !self.inlining {
490                     let items = item_ids.iter()
491                                         .map(|ii| self.cx.tcx.hir.impl_item(ii.id).clone())
492                                         .collect();
493                     let i = Impl {
494                         unsafety: unsafety,
495                         polarity: polarity,
496                         generics: gen.clone(),
497                         trait_: tr.clone(),
498                         for_: ty.clone(),
499                         items: items,
500                         attrs: item.attrs.clone(),
501                         id: item.id,
502                         whence: item.span,
503                         vis: item.vis.clone(),
504                         stab: self.stability(item.id),
505                         depr: self.deprecation(item.id),
506                     };
507                     om.impls.push(i);
508                 }
509             },
510             hir::ItemDefaultImpl(unsafety, ref trait_ref) => {
511                 // See comment above about ItemImpl.
512                 if !self.inlining {
513                     let i = DefaultImpl {
514                         unsafety: unsafety,
515                         trait_: trait_ref.clone(),
516                         id: item.id,
517                         attrs: item.attrs.clone(),
518                         whence: item.span,
519                     };
520                     om.def_traits.push(i);
521                 }
522             }
523         }
524     }
525
526     // convert each exported_macro into a doc item
527     fn visit_local_macro(&self, def: &hir::MacroDef) -> Macro {
528         let tts = def.body.trees().collect::<Vec<_>>();
529         // Extract the spans of all matchers. They represent the "interface" of the macro.
530         let matchers = tts.chunks(4).map(|arm| arm[0].span()).collect();
531
532         Macro {
533             def_id: self.cx.tcx.hir.local_def_id(def.id),
534             attrs: def.attrs.clone(),
535             name: def.name,
536             whence: def.span,
537             matchers: matchers,
538             stab: self.stability(def.id),
539             depr: self.deprecation(def.id),
540             imported_from: None,
541         }
542     }
543 }