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