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