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