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