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