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