]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/visit_ast.rs
Auto merge of #71292 - marmeladema:queries-local-def-id, 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_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};
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: ast::Name,
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: ast::Name,
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: ast::Name,
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: ast::Name,
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<ast::Name>,
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<ast::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(
379         &mut self,
380         item: &'tcx hir::Item,
381         renamed: Option<ast::Ident>,
382         om: &mut Module<'tcx>,
383     ) {
384         debug!("visiting item {:?}", item);
385         let ident = renamed.unwrap_or(item.ident);
386
387         if item.vis.node.is_pub() {
388             let def_id = self.cx.tcx.hir().local_def_id(item.hir_id);
389             self.store_path(def_id.to_def_id());
390         }
391
392         match item.kind {
393             hir::ItemKind::ForeignMod(ref fm) => {
394                 for item in fm.items {
395                     self.visit_foreign_item(item, None, om);
396                 }
397             }
398             // If we're inlining, skip private items.
399             _ if self.inlining && !item.vis.node.is_pub() => {}
400             hir::ItemKind::GlobalAsm(..) => {}
401             hir::ItemKind::ExternCrate(orig_name) => {
402                 let def_id = self.cx.tcx.hir().local_def_id(item.hir_id);
403                 om.extern_crates.push(ExternCrate {
404                     cnum: self.cx.tcx.extern_mod_stmt_cnum(def_id).unwrap_or(LOCAL_CRATE),
405                     name: ident.name,
406                     path: orig_name.map(|x| x.to_string()),
407                     vis: &item.vis,
408                     attrs: &item.attrs,
409                     whence: item.span,
410                 })
411             }
412             hir::ItemKind::Use(_, hir::UseKind::ListStem) => {}
413             hir::ItemKind::Use(ref path, kind) => {
414                 let is_glob = kind == hir::UseKind::Glob;
415
416                 // Struct and variant constructors and proc macro stubs always show up alongside
417                 // their definitions, we've already processed them so just discard these.
418                 if let Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) = path.res {
419                     return;
420                 }
421
422                 // If there was a private module in the current path then don't bother inlining
423                 // anything as it will probably be stripped anyway.
424                 if item.vis.node.is_pub() && self.inside_public_path {
425                     let please_inline = item.attrs.iter().any(|item| match item.meta_item_list() {
426                         Some(ref list) if item.check_name(sym::doc) => {
427                             list.iter().any(|i| i.check_name(sym::inline))
428                         }
429                         _ => false,
430                     });
431                     let ident = if is_glob { None } else { Some(ident) };
432                     if self.maybe_inline_local(
433                         item.hir_id,
434                         path.res,
435                         ident,
436                         is_glob,
437                         om,
438                         please_inline,
439                     ) {
440                         return;
441                     }
442                 }
443
444                 om.imports.push(Import {
445                     name: ident.name,
446                     id: item.hir_id,
447                     vis: &item.vis,
448                     attrs: &item.attrs,
449                     path,
450                     glob: is_glob,
451                     whence: item.span,
452                 });
453             }
454             hir::ItemKind::Mod(ref m) => {
455                 om.mods.push(self.visit_mod_contents(
456                     item.span,
457                     &item.attrs,
458                     &item.vis,
459                     item.hir_id,
460                     m,
461                     Some(ident.name),
462                 ));
463             }
464             hir::ItemKind::Enum(ref ed, ref gen) => {
465                 om.enums.push(self.visit_enum_def(item, ident.name, ed, gen))
466             }
467             hir::ItemKind::Struct(ref sd, ref gen) => {
468                 om.structs.push(self.visit_variant_data(item, ident.name, sd, gen))
469             }
470             hir::ItemKind::Union(ref sd, ref gen) => {
471                 om.unions.push(self.visit_union_data(item, ident.name, sd, gen))
472             }
473             hir::ItemKind::Fn(ref sig, ref gen, body) => {
474                 self.visit_fn(om, item, ident.name, &sig.decl, sig.header, gen, body)
475             }
476             hir::ItemKind::TyAlias(ty, ref gen) => {
477                 let t = Typedef {
478                     ty,
479                     gen,
480                     name: ident.name,
481                     id: item.hir_id,
482                     attrs: &item.attrs,
483                     whence: item.span,
484                     vis: &item.vis,
485                 };
486                 om.typedefs.push(t);
487             }
488             hir::ItemKind::OpaqueTy(ref opaque_ty) => {
489                 let t = OpaqueTy {
490                     opaque_ty,
491                     name: ident.name,
492                     id: item.hir_id,
493                     attrs: &item.attrs,
494                     whence: item.span,
495                     vis: &item.vis,
496                 };
497                 om.opaque_tys.push(t);
498             }
499             hir::ItemKind::Static(type_, mutability, expr) => {
500                 let s = Static {
501                     type_,
502                     mutability,
503                     expr,
504                     id: item.hir_id,
505                     name: ident.name,
506                     attrs: &item.attrs,
507                     whence: item.span,
508                     vis: &item.vis,
509                 };
510                 om.statics.push(s);
511             }
512             hir::ItemKind::Const(type_, expr) => {
513                 // Underscore constants do not correspond to a nameable item and
514                 // so are never useful in documentation.
515                 if ident.name != kw::Underscore {
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             }
528             hir::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref item_ids) => {
529                 let items = item_ids.iter().map(|ti| self.cx.tcx.hir().trait_item(ti.id)).collect();
530                 let t = Trait {
531                     is_auto,
532                     unsafety,
533                     name: ident.name,
534                     items,
535                     generics,
536                     bounds,
537                     id: item.hir_id,
538                     attrs: &item.attrs,
539                     whence: item.span,
540                     vis: &item.vis,
541                 };
542                 om.traits.push(t);
543             }
544             hir::ItemKind::TraitAlias(ref generics, ref bounds) => {
545                 let t = TraitAlias {
546                     name: ident.name,
547                     generics,
548                     bounds,
549                     id: item.hir_id,
550                     attrs: &item.attrs,
551                     whence: item.span,
552                     vis: &item.vis,
553                 };
554                 om.trait_aliases.push(t);
555             }
556
557             hir::ItemKind::Impl {
558                 unsafety,
559                 polarity,
560                 defaultness,
561                 constness,
562                 defaultness_span: _,
563                 ref generics,
564                 ref of_trait,
565                 self_ty,
566                 ref items,
567             } => {
568                 // Don't duplicate impls when inlining or if it's implementing a trait, we'll pick
569                 // them up regardless of where they're located.
570                 if !self.inlining && of_trait.is_none() {
571                     let items =
572                         items.iter().map(|item| self.cx.tcx.hir().impl_item(item.id)).collect();
573                     let i = Impl {
574                         unsafety,
575                         polarity,
576                         defaultness,
577                         constness,
578                         generics,
579                         trait_: of_trait,
580                         for_: self_ty,
581                         items,
582                         attrs: &item.attrs,
583                         id: item.hir_id,
584                         whence: item.span,
585                         vis: &item.vis,
586                     };
587                     om.impls.push(i);
588                 }
589             }
590         }
591     }
592
593     fn visit_foreign_item(
594         &mut self,
595         item: &'tcx hir::ForeignItem,
596         renamed: Option<ast::Ident>,
597         om: &mut Module<'tcx>,
598     ) {
599         // If inlining we only want to include public functions.
600         if self.inlining && !item.vis.node.is_pub() {
601             return;
602         }
603
604         om.foreigns.push(ForeignItem {
605             id: item.hir_id,
606             name: renamed.unwrap_or(item.ident).name,
607             kind: &item.kind,
608             vis: &item.vis,
609             attrs: &item.attrs,
610             whence: item.span,
611         });
612     }
613
614     // Convert each `exported_macro` into a doc item.
615     fn visit_local_macro(
616         &self,
617         def: &'tcx hir::MacroDef,
618         renamed: Option<ast::Name>,
619     ) -> Macro<'tcx> {
620         debug!("visit_local_macro: {}", def.ident);
621         let tts = def.ast.body.inner_tokens().trees().collect::<Vec<_>>();
622         // Extract the spans of all matchers. They represent the "interface" of the macro.
623         let matchers = tts.chunks(4).map(|arm| arm[0].span()).collect();
624
625         Macro {
626             hid: def.hir_id,
627             def_id: self.cx.tcx.hir().local_def_id(def.hir_id).to_def_id(),
628             attrs: &def.attrs,
629             name: renamed.unwrap_or(def.ident.name),
630             whence: def.span,
631             matchers,
632             imported_from: None,
633         }
634     }
635 }