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