]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/visit_ast.rs
Auto merge of #54265 - arielb1:civilize-proc-macros, r=alexcrichton
[rust.git] / src / librustdoc / visit_ast.rs
1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Rust AST Visitor. Extracts useful information and massages it into a form
12 //! usable for clean
13
14 use std::mem;
15
16 use syntax::ast;
17 use syntax::attr;
18 use syntax::source_map::Spanned;
19 use syntax_pos::{self, Span};
20
21 use rustc::hir::Node;
22 use rustc::hir::def::Def;
23 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
24 use rustc::middle::privacy::AccessLevel;
25 use rustc::util::nodemap::{FxHashSet, FxHashMap};
26
27 use rustc::hir;
28
29 use core;
30 use clean::{self, AttributesExt, NestedAttributesExt, def_id_to_path};
31 use doctree::*;
32
33 // looks to me like the first two of these are actually
34 // output parameters, maybe only mutated once; perhaps
35 // better simply to have the visit method return a tuple
36 // containing them?
37
38 // also, is there some reason that this doesn't use the 'visit'
39 // framework from syntax?
40
41 pub struct RustdocVisitor<'a, 'tcx: 'a, 'rcx: 'a, 'cstore: 'rcx> {
42     pub module: Module,
43     pub attrs: hir::HirVec<ast::Attribute>,
44     pub cx: &'a core::DocContext<'a, 'tcx, 'rcx, 'cstore>,
45     view_item_stack: FxHashSet<ast::NodeId>,
46     inlining: bool,
47     /// Is the current module and all of its parents public?
48     inside_public_path: bool,
49     exact_paths: Option<FxHashMap<DefId, Vec<String>>>,
50 }
51
52 impl<'a, 'tcx, 'rcx, 'cstore> RustdocVisitor<'a, 'tcx, 'rcx, 'cstore> {
53     pub fn new(
54         cx: &'a core::DocContext<'a, 'tcx, 'rcx, 'cstore>
55     ) -> RustdocVisitor<'a, 'tcx, 'rcx, 'cstore> {
56         // If the root is re-exported, terminate all recursion.
57         let mut stack = FxHashSet();
58         stack.insert(ast::CRATE_NODE_ID);
59         RustdocVisitor {
60             module: Module::new(None),
61             attrs: hir::HirVec::new(),
62             cx,
63             view_item_stack: stack,
64             inlining: false,
65             inside_public_path: true,
66             exact_paths: Some(FxHashMap()),
67         }
68     }
69
70     fn store_path(&mut self, did: DefId) {
71         // We can't use the entry api, as that keeps the mutable borrow of self active
72         // when we try to use cx
73         let exact_paths = self.exact_paths.as_mut().unwrap();
74         if exact_paths.get(&did).is_none() {
75             let path = def_id_to_path(self.cx, did, self.cx.crate_name.clone());
76             exact_paths.insert(did, path);
77         }
78     }
79
80     fn stability(&self, id: ast::NodeId) -> Option<attr::Stability> {
81         self.cx.tcx.hir.opt_local_def_id(id)
82             .and_then(|def_id| self.cx.tcx.lookup_stability(def_id)).cloned()
83     }
84
85     fn deprecation(&self, id: ast::NodeId) -> Option<attr::Deprecation> {
86         self.cx.tcx.hir.opt_local_def_id(id)
87             .and_then(|def_id| self.cx.tcx.lookup_deprecation(def_id))
88     }
89
90     pub fn visit(&mut self, krate: &hir::Crate) {
91         self.attrs = krate.attrs.clone();
92
93         self.module = self.visit_mod_contents(krate.span,
94                                               krate.attrs.clone(),
95                                               Spanned { span: syntax_pos::DUMMY_SP,
96                                                         node: hir::VisibilityKind::Public },
97                                               ast::CRATE_NODE_ID,
98                                               &krate.module,
99                                               None);
100         // attach the crate's exported macros to the top-level module:
101         let macro_exports: Vec<_> =
102             krate.exported_macros.iter().map(|def| self.visit_local_macro(def)).collect();
103         self.module.macros.extend(macro_exports);
104         self.module.is_crate = true;
105
106         self.cx.renderinfo.borrow_mut().exact_paths = self.exact_paths.take().unwrap();
107     }
108
109     pub fn visit_variant_data(&mut self, item: &hir::Item,
110                               name: ast::Name, sd: &hir::VariantData,
111                               generics: &hir::Generics) -> Struct {
112         debug!("Visiting struct");
113         let struct_type = struct_type_from_def(&*sd);
114         Struct {
115             id: item.id,
116             struct_type,
117             name,
118             vis: item.vis.clone(),
119             stab: self.stability(item.id),
120             depr: self.deprecation(item.id),
121             attrs: item.attrs.clone(),
122             generics: generics.clone(),
123             fields: sd.fields().iter().cloned().collect(),
124             whence: item.span
125         }
126     }
127
128     pub fn visit_union_data(&mut self, item: &hir::Item,
129                             name: ast::Name, sd: &hir::VariantData,
130                             generics: &hir::Generics) -> Union {
131         debug!("Visiting union");
132         let struct_type = struct_type_from_def(&*sd);
133         Union {
134             id: item.id,
135             struct_type,
136             name,
137             vis: item.vis.clone(),
138             stab: self.stability(item.id),
139             depr: self.deprecation(item.id),
140             attrs: item.attrs.clone(),
141             generics: generics.clone(),
142             fields: sd.fields().iter().cloned().collect(),
143             whence: item.span
144         }
145     }
146
147     pub fn visit_enum_def(&mut self, it: &hir::Item,
148                           name: ast::Name, def: &hir::EnumDef,
149                           params: &hir::Generics) -> Enum {
150         debug!("Visiting enum");
151         Enum {
152             name,
153             variants: def.variants.iter().map(|v| Variant {
154                 name: v.node.name,
155                 attrs: v.node.attrs.clone(),
156                 stab: self.stability(v.node.data.id()),
157                 depr: self.deprecation(v.node.data.id()),
158                 def: v.node.data.clone(),
159                 whence: v.span,
160             }).collect(),
161             vis: it.vis.clone(),
162             stab: self.stability(it.id),
163             depr: self.deprecation(it.id),
164             generics: params.clone(),
165             attrs: it.attrs.clone(),
166             id: it.id,
167             whence: it.span,
168         }
169     }
170
171     pub fn visit_fn(&mut self, item: &hir::Item,
172                     name: ast::Name, fd: &hir::FnDecl,
173                     header: hir::FnHeader,
174                     gen: &hir::Generics,
175                     body: hir::BodyId) -> Function {
176         debug!("Visiting fn");
177         Function {
178             id: item.id,
179             vis: item.vis.clone(),
180             stab: self.stability(item.id),
181             depr: self.deprecation(item.id),
182             attrs: item.attrs.clone(),
183             decl: fd.clone(),
184             name,
185             whence: item.span,
186             generics: gen.clone(),
187             header,
188             body,
189         }
190     }
191
192     pub fn visit_mod_contents(&mut self, span: Span, attrs: hir::HirVec<ast::Attribute>,
193                               vis: hir::Visibility, id: ast::NodeId,
194                               m: &hir::Mod,
195                               name: Option<ast::Name>) -> Module {
196         let mut om = Module::new(name);
197         om.where_outer = span;
198         om.where_inner = m.inner;
199         om.attrs = attrs;
200         om.vis = vis.clone();
201         om.stab = self.stability(id);
202         om.depr = self.deprecation(id);
203         om.id = id;
204         // Keep track of if there were any private modules in the path.
205         let orig_inside_public_path = self.inside_public_path;
206         self.inside_public_path &= vis.node.is_pub();
207         for i in &m.item_ids {
208             let item = self.cx.tcx.hir.expect_item(i.id);
209             self.visit_item(item, None, &mut om);
210         }
211         self.inside_public_path = orig_inside_public_path;
212         om
213     }
214
215     /// Tries to resolve the target of a `pub use` statement and inlines the
216     /// target if it is defined locally and would not be documented otherwise,
217     /// or when it is specifically requested with `please_inline`.
218     /// (the latter is the case when the import is marked `doc(inline)`)
219     ///
220     /// Cross-crate inlining occurs later on during crate cleaning
221     /// and follows different rules.
222     ///
223     /// Returns true if the target has been inlined.
224     fn maybe_inline_local(&mut self,
225                           id: ast::NodeId,
226                           def: Def,
227                           renamed: Option<ast::Name>,
228                           glob: bool,
229                           om: &mut Module,
230                           please_inline: bool) -> bool {
231
232         fn inherits_doc_hidden(cx: &core::DocContext, mut node: ast::NodeId) -> bool {
233             while let Some(id) = cx.tcx.hir.get_enclosing_scope(node) {
234                 node = id;
235                 if cx.tcx.hir.attrs(node).lists("doc").has_word("hidden") {
236                     return true;
237                 }
238                 if node == ast::CRATE_NODE_ID {
239                     break;
240                 }
241             }
242             false
243         }
244
245         debug!("maybe_inline_local def: {:?}", def);
246
247         let tcx = self.cx.tcx;
248         if def == Def::Err {
249             return false;
250         }
251         let def_did = def.def_id();
252
253         let use_attrs = tcx.hir.attrs(id);
254         // Don't inline doc(hidden) imports so they can be stripped at a later stage.
255         let is_no_inline = use_attrs.lists("doc").has_word("no_inline") ||
256                            use_attrs.lists("doc").has_word("hidden");
257
258         // For cross-crate impl inlining we need to know whether items are
259         // reachable in documentation - a previously nonreachable item can be
260         // made reachable by cross-crate inlining which we're checking here.
261         // (this is done here because we need to know this upfront)
262         if !def_did.is_local() && !is_no_inline {
263             let attrs = clean::inline::load_attrs(self.cx, def_did);
264             let self_is_hidden = attrs.lists("doc").has_word("hidden");
265             match def {
266                 Def::Trait(did) |
267                 Def::Struct(did) |
268                 Def::Union(did) |
269                 Def::Enum(did) |
270                 Def::ForeignTy(did) |
271                 Def::TyAlias(did) if !self_is_hidden => {
272                     self.cx.renderinfo
273                         .borrow_mut()
274                         .access_levels.map
275                         .insert(did, AccessLevel::Public);
276                 },
277                 Def::Mod(did) => if !self_is_hidden {
278                     ::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did);
279                 },
280                 _ => {},
281             }
282
283             return false
284         }
285
286         let def_node_id = match tcx.hir.as_local_node_id(def_did) {
287             Some(n) => n, None => return false
288         };
289
290         let is_private = !self.cx.renderinfo.borrow().access_levels.is_public(def_did);
291         let is_hidden = inherits_doc_hidden(self.cx, def_node_id);
292
293         // Only inline if requested or if the item would otherwise be stripped
294         if (!please_inline && !is_private && !is_hidden) || is_no_inline {
295             return false
296         }
297
298         if !self.view_item_stack.insert(def_node_id) { return false }
299
300         let ret = match tcx.hir.get(def_node_id) {
301             Node::Item(&hir::Item { node: hir::ItemKind::Mod(ref m), .. }) if glob => {
302                 let prev = mem::replace(&mut self.inlining, true);
303                 for i in &m.item_ids {
304                     let i = self.cx.tcx.hir.expect_item(i.id);
305                     self.visit_item(i, None, om);
306                 }
307                 self.inlining = prev;
308                 true
309             }
310             Node::Item(it) if !glob => {
311                 let prev = mem::replace(&mut self.inlining, true);
312                 self.visit_item(it, renamed, om);
313                 self.inlining = prev;
314                 true
315             }
316             Node::ForeignItem(it) if !glob => {
317                 // generate a fresh `extern {}` block if we want to inline a foreign item.
318                 om.foreigns.push(hir::ForeignMod {
319                     abi: tcx.hir.get_foreign_abi(it.id),
320                     items: vec![hir::ForeignItem {
321                         name: renamed.unwrap_or(it.name),
322                         .. it.clone()
323                     }].into(),
324                 });
325                 true
326             }
327             _ => false,
328         };
329         self.view_item_stack.remove(&def_node_id);
330         ret
331     }
332
333     pub fn visit_item(&mut self, item: &hir::Item,
334                       renamed: Option<ast::Name>, om: &mut Module) {
335         debug!("Visiting item {:?}", item);
336         let name = renamed.unwrap_or(item.name);
337
338         if item.vis.node.is_pub() {
339             let def_id = self.cx.tcx.hir.local_def_id(item.id);
340             self.store_path(def_id);
341         }
342
343         match item.node {
344             hir::ItemKind::ForeignMod(ref fm) => {
345                 // If inlining we only want to include public functions.
346                 om.foreigns.push(if self.inlining {
347                     hir::ForeignMod {
348                         abi: fm.abi,
349                         items: fm.items.iter().filter(|i| i.vis.node.is_pub()).cloned().collect(),
350                     }
351                 } else {
352                     fm.clone()
353                 });
354             }
355             // If we're inlining, skip private items.
356             _ if self.inlining && !item.vis.node.is_pub() => {}
357             hir::ItemKind::GlobalAsm(..) => {}
358             hir::ItemKind::ExternCrate(orig_name) => {
359                 let def_id = self.cx.tcx.hir.local_def_id(item.id);
360                 om.extern_crates.push(ExternCrate {
361                     cnum: self.cx.tcx.extern_mod_stmt_cnum(def_id)
362                                 .unwrap_or(LOCAL_CRATE),
363                     name,
364                     path: orig_name.map(|x|x.to_string()),
365                     vis: item.vis.clone(),
366                     attrs: item.attrs.clone(),
367                     whence: item.span,
368                 })
369             }
370             hir::ItemKind::Use(_, hir::UseKind::ListStem) => {}
371             hir::ItemKind::Use(ref path, kind) => {
372                 let is_glob = kind == hir::UseKind::Glob;
373
374                 // struct and variant constructors always show up alongside their definitions, we've
375                 // already processed them so just discard these.
376                 match path.def {
377                     Def::StructCtor(..) | Def::VariantCtor(..) | Def::SelfCtor(..) => return,
378                     _ => {}
379                 }
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.node.is_pub() && 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::ItemKind::Mod(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::ItemKind::Enum(ref ed, ref gen) =>
422                 om.enums.push(self.visit_enum_def(item, name, ed, gen)),
423             hir::ItemKind::Struct(ref sd, ref gen) =>
424                 om.structs.push(self.visit_variant_data(item, name, sd, gen)),
425             hir::ItemKind::Union(ref sd, ref gen) =>
426                 om.unions.push(self.visit_union_data(item, name, sd, gen)),
427             hir::ItemKind::Fn(ref fd, header, ref gen, body) =>
428                 om.fns.push(self.visit_fn(item, name, &**fd, header, gen, body)),
429             hir::ItemKind::Ty(ref ty, ref gen) => {
430                 let t = Typedef {
431                     ty: ty.clone(),
432                     gen: gen.clone(),
433                     name,
434                     id: item.id,
435                     attrs: item.attrs.clone(),
436                     whence: item.span,
437                     vis: item.vis.clone(),
438                     stab: self.stability(item.id),
439                     depr: self.deprecation(item.id),
440                 };
441                 om.typedefs.push(t);
442             },
443             hir::ItemKind::Existential(ref exist_ty) => {
444                 let t = Existential {
445                     exist_ty: exist_ty.clone(),
446                     name,
447                     id: item.id,
448                     attrs: item.attrs.clone(),
449                     whence: item.span,
450                     vis: item.vis.clone(),
451                     stab: self.stability(item.id),
452                     depr: self.deprecation(item.id),
453                 };
454                 om.existentials.push(t);
455             },
456             hir::ItemKind::Static(ref ty, ref mut_, ref exp) => {
457                 let s = Static {
458                     type_: ty.clone(),
459                     mutability: mut_.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.statics.push(s);
470             },
471             hir::ItemKind::Const(ref ty, ref exp) => {
472                 let s = Constant {
473                     type_: ty.clone(),
474                     expr: exp.clone(),
475                     id: item.id,
476                     name,
477                     attrs: item.attrs.clone(),
478                     whence: item.span,
479                     vis: item.vis.clone(),
480                     stab: self.stability(item.id),
481                     depr: self.deprecation(item.id),
482                 };
483                 om.constants.push(s);
484             },
485             hir::ItemKind::Trait(is_auto, unsafety, ref gen, ref b, ref item_ids) => {
486                 let items = item_ids.iter()
487                                     .map(|ti| self.cx.tcx.hir.trait_item(ti.id).clone())
488                                     .collect();
489                 let t = Trait {
490                     is_auto,
491                     unsafety,
492                     name,
493                     items,
494                     generics: gen.clone(),
495                     bounds: b.iter().cloned().collect(),
496                     id: item.id,
497                     attrs: item.attrs.clone(),
498                     whence: item.span,
499                     vis: item.vis.clone(),
500                     stab: self.stability(item.id),
501                     depr: self.deprecation(item.id),
502                 };
503                 om.traits.push(t);
504             },
505             hir::ItemKind::TraitAlias(..) => {
506                 unimplemented!("trait objects are not yet implemented")
507             },
508
509             hir::ItemKind::Impl(unsafety,
510                           polarity,
511                           defaultness,
512                           ref gen,
513                           ref tr,
514                           ref ty,
515                           ref item_ids) => {
516                 // Don't duplicate impls when inlining or if it's implementing a trait, we'll pick
517                 // them up regardless of where they're located.
518                 if !self.inlining && tr.is_none() {
519                     let items = item_ids.iter()
520                                         .map(|ii| self.cx.tcx.hir.impl_item(ii.id).clone())
521                                         .collect();
522                     let i = Impl {
523                         unsafety,
524                         polarity,
525                         defaultness,
526                         generics: gen.clone(),
527                         trait_: tr.clone(),
528                         for_: ty.clone(),
529                         items,
530                         attrs: item.attrs.clone(),
531                         id: item.id,
532                         whence: item.span,
533                         vis: item.vis.clone(),
534                         stab: self.stability(item.id),
535                         depr: self.deprecation(item.id),
536                     };
537                     om.impls.push(i);
538                 }
539             },
540         }
541     }
542
543     // convert each exported_macro into a doc item
544     fn visit_local_macro(&self, def: &hir::MacroDef) -> Macro {
545         debug!("visit_local_macro: {}", def.name);
546         let tts = def.body.trees().collect::<Vec<_>>();
547         // Extract the spans of all matchers. They represent the "interface" of the macro.
548         let matchers = tts.chunks(4).map(|arm| arm[0].span()).collect();
549
550         Macro {
551             def_id: self.cx.tcx.hir.local_def_id(def.id),
552             attrs: def.attrs.clone(),
553             name: def.name,
554             whence: def.span,
555             matchers,
556             stab: self.stability(def.id),
557             depr: self.deprecation(def.id),
558             imported_from: None,
559         }
560     }
561 }