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