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