]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/visit_ast.rs
pin docs: add some forward references
[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.has_name(sym::proc_macro) {
169                 Some(MacroKind::Bang)
170             } else if a.has_name(sym::proc_macro_derive) {
171                 Some(MacroKind::Derive)
172             } else if a.has_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.has_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             if !self_is_hidden {
307                 if let Res::Def(kind, did) = res {
308                     if kind == DefKind::Mod {
309                         crate::visit_lib::LibEmbargoVisitor::new(self.cx).visit_mod(did)
310                     } else {
311                         // All items need to be handled here in case someone wishes to link
312                         // to them with intra-doc links
313                         self.cx
314                             .renderinfo
315                             .get_mut()
316                             .access_levels
317                             .map
318                             .insert(did, AccessLevel::Public);
319                     }
320                 }
321             }
322             return false;
323         }
324
325         let res_hir_id = match res_did.as_local() {
326             Some(n) => tcx.hir().as_local_hir_id(n),
327             None => return false,
328         };
329
330         let is_private = !self.cx.renderinfo.borrow().access_levels.is_public(res_did);
331         let is_hidden = inherits_doc_hidden(self.cx, res_hir_id);
332
333         // Only inline if requested or if the item would otherwise be stripped.
334         if (!please_inline && !is_private && !is_hidden) || is_no_inline {
335             return false;
336         }
337
338         if !self.view_item_stack.insert(res_hir_id) {
339             return false;
340         }
341
342         let ret = match tcx.hir().get(res_hir_id) {
343             Node::Item(&hir::Item { kind: hir::ItemKind::Mod(ref m), .. }) if glob => {
344                 let prev = mem::replace(&mut self.inlining, true);
345                 for i in m.item_ids {
346                     let i = self.cx.tcx.hir().expect_item(i.id);
347                     self.visit_item(i, None, om);
348                 }
349                 self.inlining = prev;
350                 true
351             }
352             Node::Item(it) if !glob => {
353                 let prev = mem::replace(&mut self.inlining, true);
354                 self.visit_item(it, renamed, om);
355                 self.inlining = prev;
356                 true
357             }
358             Node::ForeignItem(it) if !glob => {
359                 let prev = mem::replace(&mut self.inlining, true);
360                 self.visit_foreign_item(it, renamed, om);
361                 self.inlining = prev;
362                 true
363             }
364             Node::MacroDef(def) if !glob => {
365                 om.macros.push(self.visit_local_macro(def, renamed.map(|i| i.name)));
366                 true
367             }
368             _ => false,
369         };
370         self.view_item_stack.remove(&res_hir_id);
371         ret
372     }
373
374     fn visit_item(
375         &mut self,
376         item: &'tcx hir::Item<'_>,
377         renamed: Option<Ident>,
378         om: &mut Module<'tcx>,
379     ) {
380         debug!("visiting item {:?}", item);
381         let ident = renamed.unwrap_or(item.ident);
382
383         if item.vis.node.is_pub() {
384             let def_id = self.cx.tcx.hir().local_def_id(item.hir_id);
385             self.store_path(def_id.to_def_id());
386         }
387
388         match item.kind {
389             hir::ItemKind::ForeignMod(ref fm) => {
390                 for item in fm.items {
391                     self.visit_foreign_item(item, None, om);
392                 }
393             }
394             // If we're inlining, skip private items.
395             _ if self.inlining && !item.vis.node.is_pub() => {}
396             hir::ItemKind::GlobalAsm(..) => {}
397             hir::ItemKind::ExternCrate(orig_name) => {
398                 let def_id = self.cx.tcx.hir().local_def_id(item.hir_id);
399                 om.extern_crates.push(ExternCrate {
400                     cnum: self.cx.tcx.extern_mod_stmt_cnum(def_id).unwrap_or(LOCAL_CRATE),
401                     name: ident.name,
402                     path: orig_name.map(|x| x.to_string()),
403                     vis: &item.vis,
404                     attrs: &item.attrs,
405                     whence: item.span,
406                 })
407             }
408             hir::ItemKind::Use(_, hir::UseKind::ListStem) => {}
409             hir::ItemKind::Use(ref path, kind) => {
410                 let is_glob = kind == hir::UseKind::Glob;
411
412                 // Struct and variant constructors and proc macro stubs always show up alongside
413                 // their definitions, we've already processed them so just discard these.
414                 if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = path.res {
415                     return;
416                 }
417
418                 // If there was a private module in the current path then don't bother inlining
419                 // anything as it will probably be stripped anyway.
420                 if item.vis.node.is_pub() && self.inside_public_path {
421                     let please_inline = item.attrs.iter().any(|item| match item.meta_item_list() {
422                         Some(ref list) if item.has_name(sym::doc) => {
423                             list.iter().any(|i| i.has_name(sym::inline))
424                         }
425                         _ => false,
426                     });
427                     let ident = if is_glob { None } else { Some(ident) };
428                     if self.maybe_inline_local(
429                         item.hir_id,
430                         path.res,
431                         ident,
432                         is_glob,
433                         om,
434                         please_inline,
435                     ) {
436                         return;
437                     }
438                 }
439
440                 om.imports.push(Import {
441                     name: ident.name,
442                     id: item.hir_id,
443                     vis: &item.vis,
444                     attrs: &item.attrs,
445                     path,
446                     glob: is_glob,
447                     whence: item.span,
448                 });
449             }
450             hir::ItemKind::Mod(ref m) => {
451                 om.mods.push(self.visit_mod_contents(
452                     item.span,
453                     &item.attrs,
454                     &item.vis,
455                     item.hir_id,
456                     m,
457                     Some(ident.name),
458                 ));
459             }
460             hir::ItemKind::Enum(ref ed, ref gen) => {
461                 om.enums.push(self.visit_enum_def(item, ident.name, ed, gen))
462             }
463             hir::ItemKind::Struct(ref sd, ref gen) => {
464                 om.structs.push(self.visit_variant_data(item, ident.name, sd, gen))
465             }
466             hir::ItemKind::Union(ref sd, ref gen) => {
467                 om.unions.push(self.visit_union_data(item, ident.name, sd, gen))
468             }
469             hir::ItemKind::Fn(ref sig, ref gen, body) => {
470                 self.visit_fn(om, item, ident.name, &sig.decl, sig.header, gen, body)
471             }
472             hir::ItemKind::TyAlias(ty, ref gen) => {
473                 let t = Typedef {
474                     ty,
475                     gen,
476                     name: ident.name,
477                     id: item.hir_id,
478                     attrs: &item.attrs,
479                     whence: item.span,
480                     vis: &item.vis,
481                 };
482                 om.typedefs.push(t);
483             }
484             hir::ItemKind::OpaqueTy(ref opaque_ty) => {
485                 let t = OpaqueTy {
486                     opaque_ty,
487                     name: ident.name,
488                     id: item.hir_id,
489                     attrs: &item.attrs,
490                     whence: item.span,
491                     vis: &item.vis,
492                 };
493                 om.opaque_tys.push(t);
494             }
495             hir::ItemKind::Static(type_, mutability, expr) => {
496                 let s = Static {
497                     type_,
498                     mutability,
499                     expr,
500                     id: item.hir_id,
501                     name: ident.name,
502                     attrs: &item.attrs,
503                     whence: item.span,
504                     vis: &item.vis,
505                 };
506                 om.statics.push(s);
507             }
508             hir::ItemKind::Const(type_, expr) => {
509                 // Underscore constants do not correspond to a nameable item and
510                 // so are never useful in documentation.
511                 if ident.name != kw::Underscore {
512                     let s = Constant {
513                         type_,
514                         expr,
515                         id: item.hir_id,
516                         name: ident.name,
517                         attrs: &item.attrs,
518                         whence: item.span,
519                         vis: &item.vis,
520                     };
521                     om.constants.push(s);
522                 }
523             }
524             hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref item_ids) => {
525                 let items = item_ids.iter().map(|ti| self.cx.tcx.hir().trait_item(ti.id)).collect();
526                 let t = Trait {
527                     is_auto,
528                     unsafety,
529                     name: ident.name,
530                     items,
531                     generics,
532                     bounds,
533                     id: item.hir_id,
534                     attrs: &item.attrs,
535                     whence: item.span,
536                     vis: &item.vis,
537                 };
538                 om.traits.push(t);
539             }
540             hir::ItemKind::TraitAlias(ref generics, ref bounds) => {
541                 let t = TraitAlias {
542                     name: ident.name,
543                     generics,
544                     bounds,
545                     id: item.hir_id,
546                     attrs: &item.attrs,
547                     whence: item.span,
548                     vis: &item.vis,
549                 };
550                 om.trait_aliases.push(t);
551             }
552
553             hir::ItemKind::Impl {
554                 unsafety,
555                 polarity,
556                 defaultness,
557                 constness,
558                 defaultness_span: _,
559                 ref generics,
560                 ref of_trait,
561                 self_ty,
562                 ref items,
563             } => {
564                 // Don't duplicate impls when inlining or if it's implementing a trait, we'll pick
565                 // them up regardless of where they're located.
566                 if !self.inlining && of_trait.is_none() {
567                     let items =
568                         items.iter().map(|item| self.cx.tcx.hir().impl_item(item.id)).collect();
569                     let i = Impl {
570                         unsafety,
571                         polarity,
572                         defaultness,
573                         constness,
574                         generics,
575                         trait_: of_trait,
576                         for_: self_ty,
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<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<Symbol>,
615     ) -> Macro<'tcx> {
616         debug!("visit_local_macro: {}", def.ident);
617         let tts = def.ast.body.inner_tokens().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).to_def_id(),
624             attrs: &def.attrs,
625             name: renamed.unwrap_or(def.ident.name),
626             whence: def.span,
627             matchers,
628             imported_from: None,
629         }
630     }
631 }