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