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