]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/visit_ast.rs
Rollup merge of #67137 - anp:tracked-panic-internals, r=eddyb
[rust.git] / src / librustdoc / visit_ast.rs
1 //! The Rust AST Visitor. Extracts useful information and massages it into a form
2 //! usable for `clean`.
3
4 use rustc::hir::def::{DefKind, Res};
5 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
6 use rustc::hir::{self, Node};
7 use rustc::middle::privacy::AccessLevel;
8 use rustc::ty::TyCtxt;
9 use rustc::util::nodemap::{FxHashMap, FxHashSet};
10 use rustc_span::hygiene::MacroKind;
11 use rustc_span::source_map::Spanned;
12 use rustc_span::symbol::sym;
13 use rustc_span::{self, Span};
14 use syntax::ast;
15
16 use std::mem;
17
18 use crate::clean::{self, AttributesExt, NestedAttributesExt};
19 use crate::core;
20 use crate::doctree::*;
21
22 // FIXME: Should this be replaced with tcx.def_path_str?
23 fn def_id_to_path(tcx: TyCtxt<'_>, did: DefId) -> Vec<String> {
24     let crate_name = tcx.crate_name(did.krate).to_string();
25     let relative = tcx.def_path(did).data.into_iter().filter_map(|elem| {
26         // extern blocks have an empty name
27         let s = elem.data.to_string();
28         if !s.is_empty() { Some(s) } else { None }
29     });
30     std::iter::once(crate_name).chain(relative).collect()
31 }
32
33 // Also, is there some reason that this doesn't use the 'visit'
34 // framework from syntax?.
35
36 pub struct RustdocVisitor<'a, 'tcx> {
37     cx: &'a mut core::DocContext<'tcx>,
38     view_item_stack: FxHashSet<hir::HirId>,
39     inlining: bool,
40     /// Are the current module and all of its parents public?
41     inside_public_path: bool,
42     exact_paths: FxHashMap<DefId, Vec<String>>,
43 }
44
45 impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> {
46     pub fn new(cx: &'a mut core::DocContext<'tcx>) -> RustdocVisitor<'a, 'tcx> {
47         // If the root is re-exported, terminate all recursion.
48         let mut stack = FxHashSet::default();
49         stack.insert(hir::CRATE_HIR_ID);
50         RustdocVisitor {
51             cx,
52             view_item_stack: stack,
53             inlining: false,
54             inside_public_path: true,
55             exact_paths: FxHashMap::default(),
56         }
57     }
58
59     fn store_path(&mut self, did: DefId) {
60         let tcx = self.cx.tcx;
61         self.exact_paths.entry(did).or_insert_with(|| def_id_to_path(tcx, did));
62     }
63
64     pub fn visit(mut self, krate: &'tcx hir::Crate) -> Module<'tcx> {
65         let mut module = self.visit_mod_contents(
66             krate.span,
67             krate.attrs,
68             &Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Public },
69             hir::CRATE_HIR_ID,
70             &krate.module,
71             None,
72         );
73         // Attach the crate's exported macros to the top-level module:
74         module
75             .macros
76             .extend(krate.exported_macros.iter().map(|def| self.visit_local_macro(def, None)));
77         module.is_crate = true;
78
79         self.cx.renderinfo.get_mut().exact_paths = self.exact_paths;
80
81         module
82     }
83
84     fn visit_variant_data(
85         &mut self,
86         item: &'tcx hir::Item,
87         name: ast::Name,
88         sd: &'tcx hir::VariantData,
89         generics: &'tcx hir::Generics,
90     ) -> Struct<'tcx> {
91         debug!("visiting struct");
92         let struct_type = struct_type_from_def(&*sd);
93         Struct {
94             id: item.hir_id,
95             struct_type,
96             name,
97             vis: &item.vis,
98             attrs: &item.attrs,
99             generics,
100             fields: sd.fields(),
101             whence: item.span,
102         }
103     }
104
105     fn visit_union_data(
106         &mut self,
107         item: &'tcx hir::Item,
108         name: ast::Name,
109         sd: &'tcx hir::VariantData,
110         generics: &'tcx hir::Generics,
111     ) -> Union<'tcx> {
112         debug!("visiting union");
113         let struct_type = struct_type_from_def(&*sd);
114         Union {
115             id: item.hir_id,
116             struct_type,
117             name,
118             vis: &item.vis,
119             attrs: &item.attrs,
120             generics,
121             fields: sd.fields(),
122             whence: item.span,
123         }
124     }
125
126     fn visit_enum_def(
127         &mut self,
128         it: &'tcx hir::Item,
129         name: ast::Name,
130         def: &'tcx hir::EnumDef,
131         generics: &'tcx hir::Generics,
132     ) -> Enum<'tcx> {
133         debug!("visiting enum");
134         Enum {
135             name,
136             variants: def
137                 .variants
138                 .iter()
139                 .map(|v| Variant {
140                     name: v.ident.name,
141                     id: v.id,
142                     attrs: &v.attrs,
143                     def: &v.data,
144                     whence: v.span,
145                 })
146                 .collect(),
147             vis: &it.vis,
148             generics,
149             attrs: &it.attrs,
150             id: it.hir_id,
151             whence: it.span,
152         }
153     }
154
155     fn visit_fn(
156         &mut self,
157         om: &mut Module<'tcx>,
158         item: &'tcx hir::Item,
159         name: ast::Name,
160         decl: &'tcx hir::FnDecl,
161         header: hir::FnHeader,
162         generics: &'tcx hir::Generics,
163         body: hir::BodyId,
164     ) {
165         debug!("visiting fn");
166         let macro_kind = item
167             .attrs
168             .iter()
169             .filter_map(|a| {
170                 if a.check_name(sym::proc_macro) {
171                     Some(MacroKind::Bang)
172                 } else if a.check_name(sym::proc_macro_derive) {
173                     Some(MacroKind::Derive)
174                 } else if a.check_name(sym::proc_macro_attribute) {
175                     Some(MacroKind::Attr)
176                 } else {
177                     None
178                 }
179             })
180             .next();
181         match macro_kind {
182             Some(kind) => {
183                 let name = if kind == MacroKind::Derive {
184                     item.attrs
185                         .lists(sym::proc_macro_derive)
186                         .filter_map(|mi| mi.ident())
187                         .next()
188                         .expect("proc-macro derives require a name")
189                         .name
190                 } else {
191                     name
192                 };
193
194                 let mut helpers = Vec::new();
195                 for mi in item.attrs.lists(sym::proc_macro_derive) {
196                     if !mi.check_name(sym::attributes) {
197                         continue;
198                     }
199
200                     if let Some(list) = mi.meta_item_list() {
201                         for inner_mi in list {
202                             if let Some(ident) = inner_mi.ident() {
203                                 helpers.push(ident.name);
204                             }
205                         }
206                     }
207                 }
208
209                 om.proc_macros.push(ProcMacro {
210                     name,
211                     id: item.hir_id,
212                     kind,
213                     helpers,
214                     attrs: &item.attrs,
215                     whence: item.span,
216                 });
217             }
218             None => {
219                 om.fns.push(Function {
220                     id: item.hir_id,
221                     vis: &item.vis,
222                     attrs: &item.attrs,
223                     decl,
224                     name,
225                     whence: item.span,
226                     generics,
227                     header,
228                     body,
229                 });
230             }
231         }
232     }
233
234     fn visit_mod_contents(
235         &mut self,
236         span: Span,
237         attrs: &'tcx [ast::Attribute],
238         vis: &'tcx hir::Visibility,
239         id: hir::HirId,
240         m: &'tcx hir::Mod<'tcx>,
241         name: Option<ast::Name>,
242     ) -> Module<'tcx> {
243         let mut om = Module::new(name, attrs, vis);
244         om.where_outer = span;
245         om.where_inner = m.inner;
246         om.id = id;
247         // Keep track of if there were any private modules in the path.
248         let orig_inside_public_path = self.inside_public_path;
249         self.inside_public_path &= vis.node.is_pub();
250         for i in m.item_ids {
251             let item = self.cx.tcx.hir().expect_item(i.id);
252             self.visit_item(item, None, &mut om);
253         }
254         self.inside_public_path = orig_inside_public_path;
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(
268         &mut self,
269         id: hir::HirId,
270         res: Res,
271         renamed: Option<ast::Ident>,
272         glob: bool,
273         om: &mut Module<'tcx>,
274         please_inline: bool,
275     ) -> bool {
276         fn inherits_doc_hidden(cx: &core::DocContext<'_>, mut node: hir::HirId) -> bool {
277             while let Some(id) = cx.tcx.hir().get_enclosing_scope(node) {
278                 node = id;
279                 if cx.tcx.hir().attrs(node).lists(sym::doc).has_word(sym::hidden) {
280                     return true;
281                 }
282                 if node == hir::CRATE_HIR_ID {
283                     break;
284                 }
285             }
286             false
287         }
288
289         debug!("maybe_inline_local res: {:?}", res);
290
291         let tcx = self.cx.tcx;
292         let res_did = if let Some(did) = res.opt_def_id() {
293             did
294         } else {
295             return false;
296         };
297
298         let use_attrs = tcx.hir().attrs(id);
299         // Don't inline `doc(hidden)` imports so they can be stripped at a later stage.
300         let is_no_inline = use_attrs.lists(sym::doc).has_word(sym::no_inline)
301             || use_attrs.lists(sym::doc).has_word(sym::hidden);
302
303         // For cross-crate impl inlining we need to know whether items are
304         // reachable in documentation -- a previously nonreachable item can be
305         // made reachable by cross-crate inlining which we're checking here.
306         // (this is done here because we need to know this upfront).
307         if !res_did.is_local() && !is_no_inline {
308             let attrs = clean::inline::load_attrs(self.cx, res_did);
309             let self_is_hidden = attrs.lists(sym::doc).has_word(sym::hidden);
310             match res {
311                 Res::Def(DefKind::Trait, did)
312                 | Res::Def(DefKind::Struct, did)
313                 | Res::Def(DefKind::Union, did)
314                 | Res::Def(DefKind::Enum, did)
315                 | Res::Def(DefKind::ForeignTy, did)
316                 | Res::Def(DefKind::TyAlias, did)
317                     if !self_is_hidden =>
318                 {
319                     self.cx.renderinfo.get_mut().access_levels.map.insert(did, AccessLevel::Public);
320                 }
321                 Res::Def(DefKind::Mod, did) => {
322                     if !self_is_hidden {
323                         crate::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did);
324                     }
325                 }
326                 _ => {}
327             }
328
329             return false;
330         }
331
332         let res_hir_id = match tcx.hir().as_local_hir_id(res_did) {
333             Some(n) => n,
334             None => return false,
335         };
336
337         let is_private = !self.cx.renderinfo.borrow().access_levels.is_public(res_did);
338         let is_hidden = inherits_doc_hidden(self.cx, res_hir_id);
339
340         // Only inline if requested or if the item would otherwise be stripped.
341         if (!please_inline && !is_private && !is_hidden) || is_no_inline {
342             return false;
343         }
344
345         if !self.view_item_stack.insert(res_hir_id) {
346             return false;
347         }
348
349         let ret = match tcx.hir().get(res_hir_id) {
350             Node::Item(&hir::Item { kind: hir::ItemKind::Mod(ref m), .. }) if glob => {
351                 let prev = mem::replace(&mut self.inlining, true);
352                 for i in m.item_ids {
353                     let i = self.cx.tcx.hir().expect_item(i.id);
354                     self.visit_item(i, None, om);
355                 }
356                 self.inlining = prev;
357                 true
358             }
359             Node::Item(it) if !glob => {
360                 let prev = mem::replace(&mut self.inlining, true);
361                 self.visit_item(it, renamed, om);
362                 self.inlining = prev;
363                 true
364             }
365             Node::ForeignItem(it) if !glob => {
366                 let prev = mem::replace(&mut self.inlining, true);
367                 self.visit_foreign_item(it, renamed, om);
368                 self.inlining = prev;
369                 true
370             }
371             Node::MacroDef(def) if !glob => {
372                 om.macros.push(self.visit_local_macro(def, renamed.map(|i| i.name)));
373                 true
374             }
375             _ => false,
376         };
377         self.view_item_stack.remove(&res_hir_id);
378         ret
379     }
380
381     fn visit_item(
382         &mut self,
383         item: &'tcx hir::Item,
384         renamed: Option<ast::Ident>,
385         om: &mut Module<'tcx>,
386     ) {
387         debug!("visiting item {:?}", item);
388         let ident = renamed.unwrap_or(item.ident);
389
390         if item.vis.node.is_pub() {
391             let def_id = self.cx.tcx.hir().local_def_id(item.hir_id);
392             self.store_path(def_id);
393         }
394
395         match item.kind {
396             hir::ItemKind::ForeignMod(ref fm) => {
397                 for item in fm.items {
398                     self.visit_foreign_item(item, None, om);
399                 }
400             }
401             // If we're inlining, skip private items.
402             _ if self.inlining && !item.vis.node.is_pub() => {}
403             hir::ItemKind::GlobalAsm(..) => {}
404             hir::ItemKind::ExternCrate(orig_name) => {
405                 let def_id = self.cx.tcx.hir().local_def_id(item.hir_id);
406                 om.extern_crates.push(ExternCrate {
407                     cnum: self.cx.tcx.extern_mod_stmt_cnum(def_id).unwrap_or(LOCAL_CRATE),
408                     name: ident.name,
409                     path: orig_name.map(|x| x.to_string()),
410                     vis: &item.vis,
411                     attrs: &item.attrs,
412                     whence: item.span,
413                 })
414             }
415             hir::ItemKind::Use(_, hir::UseKind::ListStem) => {}
416             hir::ItemKind::Use(ref path, kind) => {
417                 let is_glob = kind == hir::UseKind::Glob;
418
419                 // Struct and variant constructors and proc macro stubs always show up alongside
420                 // their definitions, we've already processed them so just discard these.
421                 if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = path.res {
422                     return;
423                 }
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.node.is_pub() && self.inside_public_path {
428                     let please_inline = item.attrs.iter().any(|item| match item.meta_item_list() {
429                         Some(ref list) if item.check_name(sym::doc) => {
430                             list.iter().any(|i| i.check_name(sym::inline))
431                         }
432                         _ => false,
433                     });
434                     let ident = if is_glob { None } else { Some(ident) };
435                     if self.maybe_inline_local(
436                         item.hir_id,
437                         path.res,
438                         ident,
439                         is_glob,
440                         om,
441                         please_inline,
442                     ) {
443                         return;
444                     }
445                 }
446
447                 om.imports.push(Import {
448                     name: ident.name,
449                     id: item.hir_id,
450                     vis: &item.vis,
451                     attrs: &item.attrs,
452                     path,
453                     glob: is_glob,
454                     whence: item.span,
455                 });
456             }
457             hir::ItemKind::Mod(ref m) => {
458                 om.mods.push(self.visit_mod_contents(
459                     item.span,
460                     &item.attrs,
461                     &item.vis,
462                     item.hir_id,
463                     m,
464                     Some(ident.name),
465                 ));
466             }
467             hir::ItemKind::Enum(ref ed, ref gen) => {
468                 om.enums.push(self.visit_enum_def(item, ident.name, ed, gen))
469             }
470             hir::ItemKind::Struct(ref sd, ref gen) => {
471                 om.structs.push(self.visit_variant_data(item, ident.name, sd, gen))
472             }
473             hir::ItemKind::Union(ref sd, ref gen) => {
474                 om.unions.push(self.visit_union_data(item, ident.name, sd, gen))
475             }
476             hir::ItemKind::Fn(ref sig, ref gen, body) => {
477                 self.visit_fn(om, item, ident.name, &sig.decl, sig.header, gen, body)
478             }
479             hir::ItemKind::TyAlias(ty, ref gen) => {
480                 let t = Typedef {
481                     ty,
482                     gen,
483                     name: ident.name,
484                     id: item.hir_id,
485                     attrs: &item.attrs,
486                     whence: item.span,
487                     vis: &item.vis,
488                 };
489                 om.typedefs.push(t);
490             }
491             hir::ItemKind::OpaqueTy(ref opaque_ty) => {
492                 let t = OpaqueTy {
493                     opaque_ty,
494                     name: ident.name,
495                     id: item.hir_id,
496                     attrs: &item.attrs,
497                     whence: item.span,
498                     vis: &item.vis,
499                 };
500                 om.opaque_tys.push(t);
501             }
502             hir::ItemKind::Static(type_, mutability, expr) => {
503                 let s = Static {
504                     type_,
505                     mutability,
506                     expr,
507                     id: item.hir_id,
508                     name: ident.name,
509                     attrs: &item.attrs,
510                     whence: item.span,
511                     vis: &item.vis,
512                 };
513                 om.statics.push(s);
514             }
515             hir::ItemKind::Const(type_, expr) => {
516                 let s = Constant {
517                     type_,
518                     expr,
519                     id: item.hir_id,
520                     name: ident.name,
521                     attrs: &item.attrs,
522                     whence: item.span,
523                     vis: &item.vis,
524                 };
525                 om.constants.push(s);
526             }
527             hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref item_ids) => {
528                 let items = item_ids.iter().map(|ti| self.cx.tcx.hir().trait_item(ti.id)).collect();
529                 let t = Trait {
530                     is_auto,
531                     unsafety,
532                     name: ident.name,
533                     items,
534                     generics,
535                     bounds,
536                     id: item.hir_id,
537                     attrs: &item.attrs,
538                     whence: item.span,
539                     vis: &item.vis,
540                 };
541                 om.traits.push(t);
542             }
543             hir::ItemKind::TraitAlias(ref generics, ref bounds) => {
544                 let t = TraitAlias {
545                     name: ident.name,
546                     generics,
547                     bounds,
548                     id: item.hir_id,
549                     attrs: &item.attrs,
550                     whence: item.span,
551                     vis: &item.vis,
552                 };
553                 om.trait_aliases.push(t);
554             }
555
556             hir::ItemKind::Impl(
557                 unsafety,
558                 polarity,
559                 defaultness,
560                 ref generics,
561                 ref trait_,
562                 for_,
563                 ref item_ids,
564             ) => {
565                 // Don't duplicate impls when inlining or if it's implementing a trait, we'll pick
566                 // them up regardless of where they're located.
567                 if !self.inlining && trait_.is_none() {
568                     let items =
569                         item_ids.iter().map(|ii| self.cx.tcx.hir().impl_item(ii.id)).collect();
570                     let i = Impl {
571                         unsafety,
572                         polarity,
573                         defaultness,
574                         generics,
575                         trait_,
576                         for_,
577                         items,
578                         attrs: &item.attrs,
579                         id: item.hir_id,
580                         whence: item.span,
581                         vis: &item.vis,
582                     };
583                     om.impls.push(i);
584                 }
585             }
586         }
587     }
588
589     fn visit_foreign_item(
590         &mut self,
591         item: &'tcx hir::ForeignItem,
592         renamed: Option<ast::Ident>,
593         om: &mut Module<'tcx>,
594     ) {
595         // If inlining we only want to include public functions.
596         if self.inlining && !item.vis.node.is_pub() {
597             return;
598         }
599
600         om.foreigns.push(ForeignItem {
601             id: item.hir_id,
602             name: renamed.unwrap_or(item.ident).name,
603             kind: &item.kind,
604             vis: &item.vis,
605             attrs: &item.attrs,
606             whence: item.span,
607         });
608     }
609
610     // Convert each `exported_macro` into a doc item.
611     fn visit_local_macro(
612         &self,
613         def: &'tcx hir::MacroDef,
614         renamed: Option<ast::Name>,
615     ) -> Macro<'tcx> {
616         debug!("visit_local_macro: {}", def.name);
617         let tts = def.body.trees().collect::<Vec<_>>();
618         // Extract the spans of all matchers. They represent the "interface" of the macro.
619         let matchers = tts.chunks(4).map(|arm| arm[0].span()).collect();
620
621         Macro {
622             hid: def.hir_id,
623             def_id: self.cx.tcx.hir().local_def_id(def.hir_id),
624             attrs: &def.attrs,
625             name: renamed.unwrap_or(def.name),
626             whence: def.span,
627             matchers,
628             imported_from: None,
629         }
630     }
631 }