]> git.lizzy.rs Git - rust.git/blob - src/librustc_save_analysis/dump_visitor.rs
ast/parser: fuse `static` & `const` grammars in all contexts.
[rust.git] / src / librustc_save_analysis / dump_visitor.rs
1 //! Write the output of rustc's analysis to an implementor of Dump.
2 //!
3 //! Dumping the analysis is implemented by walking the AST and getting a bunch of
4 //! info out from all over the place. We use `DefId`s to identify objects. The
5 //! tricky part is getting syntactic (span, source text) and semantic (reference
6 //! `DefId`s) information for parts of expressions which the compiler has discarded.
7 //! E.g., in a path `foo::bar::baz`, the compiler only keeps a span for the whole
8 //! path and a reference to `baz`, but we want spans and references for all three
9 //! idents.
10 //!
11 //! SpanUtils is used to manipulate spans. In particular, to extract sub-spans
12 //! from spans (e.g., the span for `bar` from the above example path).
13 //! DumpVisitor walks the AST and processes it, and Dumper is used for
14 //! recording the output.
15
16 use rustc::session::config::Input;
17 use rustc::span_bug;
18 use rustc::ty::{self, DefIdTree, TyCtxt};
19 use rustc_ast_pretty::pprust::{bounds_to_string, generic_params_to_string, ty_to_string};
20 use rustc_data_structures::fx::FxHashSet;
21 use rustc_hir::def::{DefKind as HirDefKind, Res};
22 use rustc_hir::def_id::DefId;
23 use rustc_span::source_map::{respan, DUMMY_SP};
24 use rustc_span::*;
25 use syntax::ast::{self, Attribute, NodeId, PatKind};
26 use syntax::ptr::P;
27 use syntax::token;
28 use syntax::visit::{self, Visitor};
29 use syntax::walk_list;
30
31 use std::env;
32 use std::path::Path;
33
34 use crate::dumper::{Access, Dumper};
35 use crate::sig;
36 use crate::span_utils::SpanUtils;
37 use crate::{
38     escape, generated_code, id_from_def_id, id_from_node_id, lower_attributes, PathCollector,
39     SaveContext,
40 };
41
42 use rls_data::{
43     CompilationOptions, CratePreludeData, Def, DefKind, GlobalCrateId, Import, ImportKind, Ref,
44     RefKind, Relation, RelationKind, SpanData,
45 };
46
47 use log::{debug, error};
48
49 macro_rules! down_cast_data {
50     ($id:ident, $kind:ident, $sp:expr) => {
51         let $id = if let super::Data::$kind(data) = $id {
52             data
53         } else {
54             span_bug!($sp, "unexpected data kind: {:?}", $id);
55         };
56     };
57 }
58
59 macro_rules! access_from {
60     ($save_ctxt:expr, $item:expr, $id:expr) => {
61         Access {
62             public: $item.vis.node.is_pub(),
63             reachable: $save_ctxt.access_levels.is_reachable($id),
64         }
65     };
66 }
67
68 macro_rules! access_from_vis {
69     ($save_ctxt:expr, $vis:expr, $id:expr) => {
70         Access { public: $vis.node.is_pub(), reachable: $save_ctxt.access_levels.is_reachable($id) }
71     };
72 }
73
74 pub struct DumpVisitor<'l, 'tcx> {
75     pub save_ctxt: SaveContext<'l, 'tcx>,
76     tcx: TyCtxt<'tcx>,
77     dumper: Dumper,
78
79     span: SpanUtils<'l>,
80     // Set of macro definition (callee) spans, and the set
81     // of macro use (callsite) spans. We store these to ensure
82     // we only write one macro def per unique macro definition, and
83     // one macro use per unique callsite span.
84     // mac_defs: FxHashSet<Span>,
85     // macro_calls: FxHashSet<Span>,
86 }
87
88 impl<'l, 'tcx> DumpVisitor<'l, 'tcx> {
89     pub fn new(save_ctxt: SaveContext<'l, 'tcx>) -> DumpVisitor<'l, 'tcx> {
90         let span_utils = SpanUtils::new(&save_ctxt.tcx.sess);
91         let dumper = Dumper::new(save_ctxt.config.clone());
92         DumpVisitor {
93             tcx: save_ctxt.tcx,
94             save_ctxt,
95             dumper,
96             span: span_utils,
97             // mac_defs: FxHashSet::default(),
98             // macro_calls: FxHashSet::default(),
99         }
100     }
101
102     pub fn analysis(&self) -> &rls_data::Analysis {
103         self.dumper.analysis()
104     }
105
106     fn nest_tables<F>(&mut self, item_id: NodeId, f: F)
107     where
108         F: FnOnce(&mut Self),
109     {
110         let item_def_id = self.tcx.hir().local_def_id_from_node_id(item_id);
111
112         let tables = if self.tcx.has_typeck_tables(item_def_id) {
113             self.tcx.typeck_tables_of(item_def_id)
114         } else {
115             self.save_ctxt.empty_tables
116         };
117
118         let old_tables = self.save_ctxt.tables;
119         self.save_ctxt.tables = tables;
120         f(self);
121         self.save_ctxt.tables = old_tables;
122     }
123
124     fn span_from_span(&self, span: Span) -> SpanData {
125         self.save_ctxt.span_from_span(span)
126     }
127
128     fn lookup_def_id(&self, ref_id: NodeId) -> Option<DefId> {
129         self.save_ctxt.lookup_def_id(ref_id)
130     }
131
132     pub fn dump_crate_info(&mut self, name: &str, krate: &ast::Crate) {
133         let source_file = self.tcx.sess.local_crate_source_file.as_ref();
134         let crate_root = source_file.map(|source_file| {
135             let source_file = Path::new(source_file);
136             match source_file.file_name() {
137                 Some(_) => source_file.parent().unwrap().display(),
138                 None => source_file.display(),
139             }
140             .to_string()
141         });
142
143         let data = CratePreludeData {
144             crate_id: GlobalCrateId {
145                 name: name.into(),
146                 disambiguator: self
147                     .tcx
148                     .sess
149                     .local_crate_disambiguator()
150                     .to_fingerprint()
151                     .as_value(),
152             },
153             crate_root: crate_root.unwrap_or_else(|| "<no source>".to_owned()),
154             external_crates: self.save_ctxt.get_external_crates(),
155             span: self.span_from_span(krate.span),
156         };
157
158         self.dumper.crate_prelude(data);
159     }
160
161     pub fn dump_compilation_options(&mut self, input: &Input, crate_name: &str) {
162         // Apply possible `remap-path-prefix` remapping to the input source file
163         // (and don't include remapping args anymore)
164         let (program, arguments) = {
165             let remap_arg_indices = {
166                 let mut indices = FxHashSet::default();
167                 // Args are guaranteed to be valid UTF-8 (checked early)
168                 for (i, e) in env::args().enumerate() {
169                     if e.starts_with("--remap-path-prefix=") {
170                         indices.insert(i);
171                     } else if e == "--remap-path-prefix" {
172                         indices.insert(i);
173                         indices.insert(i + 1);
174                     }
175                 }
176                 indices
177             };
178
179             let mut args = env::args()
180                 .enumerate()
181                 .filter(|(i, _)| !remap_arg_indices.contains(i))
182                 .map(|(_, arg)| match input {
183                     Input::File(ref path) if path == Path::new(&arg) => {
184                         let mapped = &self.tcx.sess.local_crate_source_file;
185                         mapped.as_ref().unwrap().to_string_lossy().into()
186                     }
187                     _ => arg,
188                 });
189
190             (args.next().unwrap(), args.collect())
191         };
192
193         let data = CompilationOptions {
194             directory: self.tcx.sess.working_dir.0.clone(),
195             program,
196             arguments,
197             output: self.save_ctxt.compilation_output(crate_name),
198         };
199
200         self.dumper.compilation_opts(data);
201     }
202
203     fn write_sub_paths(&mut self, path: &ast::Path) {
204         for seg in &path.segments {
205             if let Some(data) = self.save_ctxt.get_path_segment_data(seg) {
206                 self.dumper.dump_ref(data);
207             }
208         }
209     }
210
211     // As write_sub_paths, but does not process the last ident in the path (assuming it
212     // will be processed elsewhere). See note on write_sub_paths about global.
213     fn write_sub_paths_truncated(&mut self, path: &ast::Path) {
214         for seg in &path.segments[..path.segments.len() - 1] {
215             if let Some(data) = self.save_ctxt.get_path_segment_data(seg) {
216                 self.dumper.dump_ref(data);
217             }
218         }
219     }
220
221     fn process_formals(&mut self, formals: &'l [ast::Param], qualname: &str) {
222         for arg in formals {
223             self.visit_pat(&arg.pat);
224             let mut collector = PathCollector::new();
225             collector.visit_pat(&arg.pat);
226
227             for (id, ident, ..) in collector.collected_idents {
228                 let hir_id = self.tcx.hir().node_to_hir_id(id);
229                 let typ = match self.save_ctxt.tables.node_type_opt(hir_id) {
230                     Some(s) => s.to_string(),
231                     None => continue,
232                 };
233                 if !self.span.filter_generated(ident.span) {
234                     let id = id_from_node_id(id, &self.save_ctxt);
235                     let span = self.span_from_span(ident.span);
236
237                     self.dumper.dump_def(
238                         &Access { public: false, reachable: false },
239                         Def {
240                             kind: DefKind::Local,
241                             id,
242                             span,
243                             name: ident.to_string(),
244                             qualname: format!("{}::{}", qualname, ident.to_string()),
245                             value: typ,
246                             parent: None,
247                             children: vec![],
248                             decl_id: None,
249                             docs: String::new(),
250                             sig: None,
251                             attributes: vec![],
252                         },
253                     );
254                 }
255             }
256         }
257     }
258
259     fn process_method(
260         &mut self,
261         sig: &'l ast::FnSig,
262         body: Option<&'l ast::Block>,
263         id: ast::NodeId,
264         ident: ast::Ident,
265         generics: &'l ast::Generics,
266         vis: ast::Visibility,
267         span: Span,
268     ) {
269         debug!("process_method: {}:{}", id, ident);
270
271         let hir_id = self.tcx.hir().node_to_hir_id(id);
272         self.nest_tables(id, |v| {
273             if let Some(mut method_data) = v.save_ctxt.get_method_data(id, ident, span) {
274                 v.process_formals(&sig.decl.inputs, &method_data.qualname);
275                 v.process_generic_params(&generics, &method_data.qualname, id);
276
277                 method_data.value = crate::make_signature(&sig.decl, &generics);
278                 method_data.sig = sig::method_signature(id, ident, generics, sig, &v.save_ctxt);
279
280                 v.dumper.dump_def(&access_from_vis!(v.save_ctxt, vis, hir_id), method_data);
281             }
282
283             // walk arg and return types
284             for arg in &sig.decl.inputs {
285                 v.visit_ty(&arg.ty);
286             }
287
288             if let ast::FunctionRetTy::Ty(ref ret_ty) = sig.decl.output {
289                 // In async functions, return types are desugared and redefined
290                 // as an `impl Trait` existential type. Because of this, to match
291                 // the definition paths when resolving nested types we need to
292                 // start walking from the newly-created definition.
293                 match sig.header.asyncness {
294                     ast::Async::Yes { return_impl_trait_id, .. } => {
295                         v.nest_tables(return_impl_trait_id, |v| v.visit_ty(ret_ty))
296                     }
297                     _ => v.visit_ty(ret_ty),
298                 }
299             }
300
301             // walk the fn body
302             if let Some(body) = body {
303                 v.visit_block(body);
304             }
305         });
306     }
307
308     fn process_struct_field_def(&mut self, field: &ast::StructField, parent_id: NodeId) {
309         let field_data = self.save_ctxt.get_field_data(field, parent_id);
310         if let Some(field_data) = field_data {
311             let hir_id = self.tcx.hir().node_to_hir_id(field.id);
312             self.dumper.dump_def(&access_from!(self.save_ctxt, field, hir_id), field_data);
313         }
314     }
315
316     // Dump generic params bindings, then visit_generics
317     fn process_generic_params(&mut self, generics: &'l ast::Generics, prefix: &str, id: NodeId) {
318         for param in &generics.params {
319             match param.kind {
320                 ast::GenericParamKind::Lifetime { .. } => {}
321                 ast::GenericParamKind::Type { .. } => {
322                     let param_ss = param.ident.span;
323                     let name = escape(self.span.snippet(param_ss));
324                     // Append $id to name to make sure each one is unique.
325                     let qualname = format!("{}::{}${}", prefix, name, id);
326                     if !self.span.filter_generated(param_ss) {
327                         let id = id_from_node_id(param.id, &self.save_ctxt);
328                         let span = self.span_from_span(param_ss);
329
330                         self.dumper.dump_def(
331                             &Access { public: false, reachable: false },
332                             Def {
333                                 kind: DefKind::Type,
334                                 id,
335                                 span,
336                                 name,
337                                 qualname,
338                                 value: String::new(),
339                                 parent: None,
340                                 children: vec![],
341                                 decl_id: None,
342                                 docs: String::new(),
343                                 sig: None,
344                                 attributes: vec![],
345                             },
346                         );
347                     }
348                 }
349                 ast::GenericParamKind::Const { .. } => {}
350             }
351         }
352         self.visit_generics(generics);
353     }
354
355     fn process_fn(
356         &mut self,
357         item: &'l ast::Item,
358         decl: &'l ast::FnDecl,
359         header: &'l ast::FnHeader,
360         ty_params: &'l ast::Generics,
361         body: Option<&'l ast::Block>,
362     ) {
363         let hir_id = self.tcx.hir().node_to_hir_id(item.id);
364         self.nest_tables(item.id, |v| {
365             if let Some(fn_data) = v.save_ctxt.get_item_data(item) {
366                 down_cast_data!(fn_data, DefData, item.span);
367                 v.process_formals(&decl.inputs, &fn_data.qualname);
368                 v.process_generic_params(ty_params, &fn_data.qualname, item.id);
369
370                 v.dumper.dump_def(&access_from!(v.save_ctxt, item, hir_id), fn_data);
371             }
372
373             for arg in &decl.inputs {
374                 v.visit_ty(&arg.ty)
375             }
376
377             if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
378                 if let ast::TyKind::ImplTrait(..) = ret_ty.kind {
379                     // FIXME: Opaque type desugaring prevents us from easily
380                     // processing trait bounds. See `visit_ty` for more details.
381                 } else {
382                     // In async functions, return types are desugared and redefined
383                     // as an `impl Trait` existential type. Because of this, to match
384                     // the definition paths when resolving nested types we need to
385                     // start walking from the newly-created definition.
386                     match header.asyncness {
387                         ast::Async::Yes { return_impl_trait_id, .. } => {
388                             v.nest_tables(return_impl_trait_id, |v| v.visit_ty(ret_ty))
389                         }
390                         _ => v.visit_ty(ret_ty),
391                     }
392                 }
393             }
394
395             walk_list!(v, visit_block, body);
396         });
397     }
398
399     fn process_static_or_const_item(
400         &mut self,
401         item: &'l ast::Item,
402         typ: &'l ast::Ty,
403         expr: Option<&'l ast::Expr>,
404     ) {
405         let hir_id = self.tcx.hir().node_to_hir_id(item.id);
406         self.nest_tables(item.id, |v| {
407             if let Some(var_data) = v.save_ctxt.get_item_data(item) {
408                 down_cast_data!(var_data, DefData, item.span);
409                 v.dumper.dump_def(&access_from!(v.save_ctxt, item, hir_id), var_data);
410             }
411             v.visit_ty(&typ);
412             walk_list!(v, visit_expr, expr);
413         });
414     }
415
416     fn process_assoc_const(
417         &mut self,
418         id: ast::NodeId,
419         ident: ast::Ident,
420         typ: &'l ast::Ty,
421         expr: Option<&'l ast::Expr>,
422         parent_id: DefId,
423         vis: ast::Visibility,
424         attrs: &'l [Attribute],
425     ) {
426         let qualname =
427             format!("::{}", self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(id)));
428
429         if !self.span.filter_generated(ident.span) {
430             let sig = sig::assoc_const_signature(id, ident.name, typ, expr, &self.save_ctxt);
431             let span = self.span_from_span(ident.span);
432             let hir_id = self.tcx.hir().node_to_hir_id(id);
433
434             self.dumper.dump_def(
435                 &access_from_vis!(self.save_ctxt, vis, hir_id),
436                 Def {
437                     kind: DefKind::Const,
438                     id: id_from_node_id(id, &self.save_ctxt),
439                     span,
440                     name: ident.name.to_string(),
441                     qualname,
442                     value: ty_to_string(&typ),
443                     parent: Some(id_from_def_id(parent_id)),
444                     children: vec![],
445                     decl_id: None,
446                     docs: self.save_ctxt.docs_for_attrs(attrs),
447                     sig,
448                     attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
449                 },
450             );
451         }
452
453         // walk type and init value
454         self.nest_tables(id, |v| {
455             v.visit_ty(typ);
456             if let Some(expr) = expr {
457                 v.visit_expr(expr);
458             }
459         });
460     }
461
462     // FIXME tuple structs should generate tuple-specific data.
463     fn process_struct(
464         &mut self,
465         item: &'l ast::Item,
466         def: &'l ast::VariantData,
467         ty_params: &'l ast::Generics,
468     ) {
469         debug!("process_struct {:?} {:?}", item, item.span);
470         let name = item.ident.to_string();
471         let qualname = format!(
472             "::{}",
473             self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id))
474         );
475
476         let kind = match item.kind {
477             ast::ItemKind::Struct(_, _) => DefKind::Struct,
478             ast::ItemKind::Union(_, _) => DefKind::Union,
479             _ => unreachable!(),
480         };
481
482         let (value, fields) = match item.kind {
483             ast::ItemKind::Struct(ast::VariantData::Struct(ref fields, ..), ..)
484             | ast::ItemKind::Union(ast::VariantData::Struct(ref fields, ..), ..) => {
485                 let include_priv_fields = !self.save_ctxt.config.pub_only;
486                 let fields_str = fields
487                     .iter()
488                     .enumerate()
489                     .filter_map(|(i, f)| {
490                         if include_priv_fields || f.vis.node.is_pub() {
491                             f.ident.map(|i| i.to_string()).or_else(|| Some(i.to_string()))
492                         } else {
493                             None
494                         }
495                     })
496                     .collect::<Vec<_>>()
497                     .join(", ");
498                 let value = format!("{} {{ {} }}", name, fields_str);
499                 (value, fields.iter().map(|f| id_from_node_id(f.id, &self.save_ctxt)).collect())
500             }
501             _ => (String::new(), vec![]),
502         };
503
504         if !self.span.filter_generated(item.ident.span) {
505             let span = self.span_from_span(item.ident.span);
506             let hir_id = self.tcx.hir().node_to_hir_id(item.id);
507             self.dumper.dump_def(
508                 &access_from!(self.save_ctxt, item, hir_id),
509                 Def {
510                     kind,
511                     id: id_from_node_id(item.id, &self.save_ctxt),
512                     span,
513                     name,
514                     qualname: qualname.clone(),
515                     value,
516                     parent: None,
517                     children: fields,
518                     decl_id: None,
519                     docs: self.save_ctxt.docs_for_attrs(&item.attrs),
520                     sig: sig::item_signature(item, &self.save_ctxt),
521                     attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
522                 },
523             );
524         }
525
526         self.nest_tables(item.id, |v| {
527             for field in def.fields() {
528                 v.process_struct_field_def(field, item.id);
529                 v.visit_ty(&field.ty);
530             }
531
532             v.process_generic_params(ty_params, &qualname, item.id);
533         });
534     }
535
536     fn process_enum(
537         &mut self,
538         item: &'l ast::Item,
539         enum_definition: &'l ast::EnumDef,
540         ty_params: &'l ast::Generics,
541     ) {
542         let enum_data = self.save_ctxt.get_item_data(item);
543         let enum_data = match enum_data {
544             None => return,
545             Some(data) => data,
546         };
547         down_cast_data!(enum_data, DefData, item.span);
548
549         let hir_id = self.tcx.hir().node_to_hir_id(item.id);
550         let access = access_from!(self.save_ctxt, item, hir_id);
551
552         for variant in &enum_definition.variants {
553             let name = variant.ident.name.to_string();
554             let qualname = format!("{}::{}", enum_data.qualname, name);
555             let name_span = variant.ident.span;
556
557             match variant.data {
558                 ast::VariantData::Struct(ref fields, ..) => {
559                     let fields_str = fields
560                         .iter()
561                         .enumerate()
562                         .map(|(i, f)| {
563                             f.ident.map(|i| i.to_string()).unwrap_or_else(|| i.to_string())
564                         })
565                         .collect::<Vec<_>>()
566                         .join(", ");
567                     let value = format!("{}::{} {{ {} }}", enum_data.name, name, fields_str);
568                     if !self.span.filter_generated(name_span) {
569                         let span = self.span_from_span(name_span);
570                         let id = id_from_node_id(variant.id, &self.save_ctxt);
571                         let parent = Some(id_from_node_id(item.id, &self.save_ctxt));
572
573                         self.dumper.dump_def(
574                             &access,
575                             Def {
576                                 kind: DefKind::StructVariant,
577                                 id,
578                                 span,
579                                 name,
580                                 qualname,
581                                 value,
582                                 parent,
583                                 children: vec![],
584                                 decl_id: None,
585                                 docs: self.save_ctxt.docs_for_attrs(&variant.attrs),
586                                 sig: sig::variant_signature(variant, &self.save_ctxt),
587                                 attributes: lower_attributes(
588                                     variant.attrs.clone(),
589                                     &self.save_ctxt,
590                                 ),
591                             },
592                         );
593                     }
594                 }
595                 ref v => {
596                     let mut value = format!("{}::{}", enum_data.name, name);
597                     if let &ast::VariantData::Tuple(ref fields, _) = v {
598                         value.push('(');
599                         value.push_str(
600                             &fields
601                                 .iter()
602                                 .map(|f| ty_to_string(&f.ty))
603                                 .collect::<Vec<_>>()
604                                 .join(", "),
605                         );
606                         value.push(')');
607                     }
608                     if !self.span.filter_generated(name_span) {
609                         let span = self.span_from_span(name_span);
610                         let id = id_from_node_id(variant.id, &self.save_ctxt);
611                         let parent = Some(id_from_node_id(item.id, &self.save_ctxt));
612
613                         self.dumper.dump_def(
614                             &access,
615                             Def {
616                                 kind: DefKind::TupleVariant,
617                                 id,
618                                 span,
619                                 name,
620                                 qualname,
621                                 value,
622                                 parent,
623                                 children: vec![],
624                                 decl_id: None,
625                                 docs: self.save_ctxt.docs_for_attrs(&variant.attrs),
626                                 sig: sig::variant_signature(variant, &self.save_ctxt),
627                                 attributes: lower_attributes(
628                                     variant.attrs.clone(),
629                                     &self.save_ctxt,
630                                 ),
631                             },
632                         );
633                     }
634                 }
635             }
636
637             for field in variant.data.fields() {
638                 self.process_struct_field_def(field, variant.id);
639                 self.visit_ty(&field.ty);
640             }
641         }
642         self.process_generic_params(ty_params, &enum_data.qualname, item.id);
643         self.dumper.dump_def(&access, enum_data);
644     }
645
646     fn process_impl(
647         &mut self,
648         item: &'l ast::Item,
649         generics: &'l ast::Generics,
650         trait_ref: &'l Option<ast::TraitRef>,
651         typ: &'l ast::Ty,
652         impl_items: &'l [P<ast::AssocItem>],
653     ) {
654         if let Some(impl_data) = self.save_ctxt.get_item_data(item) {
655             if !self.span.filter_generated(item.span) {
656                 if let super::Data::RelationData(rel, imp) = impl_data {
657                     self.dumper.dump_relation(rel);
658                     self.dumper.dump_impl(imp);
659                 } else {
660                     span_bug!(item.span, "unexpected data kind: {:?}", impl_data);
661                 }
662             }
663         }
664
665         let map = &self.tcx.hir();
666         self.nest_tables(item.id, |v| {
667             v.visit_ty(&typ);
668             if let &Some(ref trait_ref) = trait_ref {
669                 v.process_path(trait_ref.ref_id, &trait_ref.path);
670             }
671             v.process_generic_params(generics, "", item.id);
672             for impl_item in impl_items {
673                 v.process_impl_item(impl_item, map.local_def_id_from_node_id(item.id));
674             }
675         });
676     }
677
678     fn process_trait(
679         &mut self,
680         item: &'l ast::Item,
681         generics: &'l ast::Generics,
682         trait_refs: &'l ast::GenericBounds,
683         methods: &'l [P<ast::AssocItem>],
684     ) {
685         let name = item.ident.to_string();
686         let qualname = format!(
687             "::{}",
688             self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id))
689         );
690         let mut val = name.clone();
691         if !generics.params.is_empty() {
692             val.push_str(&generic_params_to_string(&generics.params));
693         }
694         if !trait_refs.is_empty() {
695             val.push_str(": ");
696             val.push_str(&bounds_to_string(trait_refs));
697         }
698         if !self.span.filter_generated(item.ident.span) {
699             let id = id_from_node_id(item.id, &self.save_ctxt);
700             let span = self.span_from_span(item.ident.span);
701             let children = methods.iter().map(|i| id_from_node_id(i.id, &self.save_ctxt)).collect();
702             let hir_id = self.tcx.hir().node_to_hir_id(item.id);
703             self.dumper.dump_def(
704                 &access_from!(self.save_ctxt, item, hir_id),
705                 Def {
706                     kind: DefKind::Trait,
707                     id,
708                     span,
709                     name,
710                     qualname: qualname.clone(),
711                     value: val,
712                     parent: None,
713                     children,
714                     decl_id: None,
715                     docs: self.save_ctxt.docs_for_attrs(&item.attrs),
716                     sig: sig::item_signature(item, &self.save_ctxt),
717                     attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
718                 },
719             );
720         }
721
722         // super-traits
723         for super_bound in trait_refs.iter() {
724             let trait_ref = match *super_bound {
725                 ast::GenericBound::Trait(ref trait_ref, _) => trait_ref,
726                 ast::GenericBound::Outlives(..) => continue,
727             };
728
729             let trait_ref = &trait_ref.trait_ref;
730             if let Some(id) = self.lookup_def_id(trait_ref.ref_id) {
731                 let sub_span = trait_ref.path.segments.last().unwrap().ident.span;
732                 if !self.span.filter_generated(sub_span) {
733                     let span = self.span_from_span(sub_span);
734                     self.dumper.dump_ref(Ref {
735                         kind: RefKind::Type,
736                         span: span.clone(),
737                         ref_id: id_from_def_id(id),
738                     });
739
740                     self.dumper.dump_relation(Relation {
741                         kind: RelationKind::SuperTrait,
742                         span,
743                         from: id_from_def_id(id),
744                         to: id_from_node_id(item.id, &self.save_ctxt),
745                     });
746                 }
747             }
748         }
749
750         // walk generics and methods
751         self.process_generic_params(generics, &qualname, item.id);
752         for method in methods {
753             let map = &self.tcx.hir();
754             self.process_trait_item(method, map.local_def_id_from_node_id(item.id))
755         }
756     }
757
758     // `item` is the module in question, represented as an item.
759     fn process_mod(&mut self, item: &ast::Item) {
760         if let Some(mod_data) = self.save_ctxt.get_item_data(item) {
761             down_cast_data!(mod_data, DefData, item.span);
762             let hir_id = self.tcx.hir().node_to_hir_id(item.id);
763             self.dumper.dump_def(&access_from!(self.save_ctxt, item, hir_id), mod_data);
764         }
765     }
766
767     fn dump_path_ref(&mut self, id: NodeId, path: &ast::Path) {
768         let path_data = self.save_ctxt.get_path_data(id, path);
769         if let Some(path_data) = path_data {
770             self.dumper.dump_ref(path_data);
771         }
772     }
773
774     fn process_path(&mut self, id: NodeId, path: &'l ast::Path) {
775         if self.span.filter_generated(path.span) {
776             return;
777         }
778         self.dump_path_ref(id, path);
779
780         // Type arguments
781         for seg in &path.segments {
782             if let Some(ref generic_args) = seg.args {
783                 match **generic_args {
784                     ast::GenericArgs::AngleBracketed(ref data) => {
785                         for arg in &data.args {
786                             if let ast::GenericArg::Type(ty) = arg {
787                                 self.visit_ty(ty);
788                             }
789                         }
790                     }
791                     ast::GenericArgs::Parenthesized(ref data) => {
792                         for t in &data.inputs {
793                             self.visit_ty(t);
794                         }
795                         if let ast::FunctionRetTy::Ty(ty) = &data.output {
796                             self.visit_ty(ty);
797                         }
798                     }
799                 }
800             }
801         }
802
803         self.write_sub_paths_truncated(path);
804     }
805
806     fn process_struct_lit(
807         &mut self,
808         ex: &'l ast::Expr,
809         path: &'l ast::Path,
810         fields: &'l [ast::Field],
811         variant: &'l ty::VariantDef,
812         base: &'l Option<P<ast::Expr>>,
813     ) {
814         if let Some(struct_lit_data) = self.save_ctxt.get_expr_data(ex) {
815             self.write_sub_paths_truncated(path);
816             down_cast_data!(struct_lit_data, RefData, ex.span);
817             if !generated_code(ex.span) {
818                 self.dumper.dump_ref(struct_lit_data);
819             }
820
821             for field in fields {
822                 if let Some(field_data) = self.save_ctxt.get_field_ref_data(field, variant) {
823                     self.dumper.dump_ref(field_data);
824                 }
825
826                 self.visit_expr(&field.expr)
827             }
828         }
829
830         walk_list!(self, visit_expr, base);
831     }
832
833     fn process_method_call(
834         &mut self,
835         ex: &'l ast::Expr,
836         seg: &'l ast::PathSegment,
837         args: &'l [P<ast::Expr>],
838     ) {
839         debug!("process_method_call {:?} {:?}", ex, ex.span);
840         if let Some(mcd) = self.save_ctxt.get_expr_data(ex) {
841             down_cast_data!(mcd, RefData, ex.span);
842             if !generated_code(ex.span) {
843                 self.dumper.dump_ref(mcd);
844             }
845         }
846
847         // Explicit types in the turbo-fish.
848         if let Some(ref generic_args) = seg.args {
849             if let ast::GenericArgs::AngleBracketed(ref data) = **generic_args {
850                 for arg in &data.args {
851                     match arg {
852                         ast::GenericArg::Type(ty) => self.visit_ty(ty),
853                         _ => {}
854                     }
855                 }
856             }
857         }
858
859         // walk receiver and args
860         walk_list!(self, visit_expr, args);
861     }
862
863     fn process_pat(&mut self, p: &'l ast::Pat) {
864         match p.kind {
865             PatKind::Struct(ref _path, ref fields, _) => {
866                 // FIXME do something with _path?
867                 let hir_id = self.tcx.hir().node_to_hir_id(p.id);
868                 let adt = match self.save_ctxt.tables.node_type_opt(hir_id) {
869                     Some(ty) if ty.ty_adt_def().is_some() => ty.ty_adt_def().unwrap(),
870                     _ => {
871                         visit::walk_pat(self, p);
872                         return;
873                     }
874                 };
875                 let variant = adt.variant_of_res(self.save_ctxt.get_path_res(p.id));
876
877                 for field in fields {
878                     if let Some(index) = self.tcx.find_field_index(field.ident, variant) {
879                         if !self.span.filter_generated(field.ident.span) {
880                             let span = self.span_from_span(field.ident.span);
881                             self.dumper.dump_ref(Ref {
882                                 kind: RefKind::Variable,
883                                 span,
884                                 ref_id: id_from_def_id(variant.fields[index].did),
885                             });
886                         }
887                     }
888                     self.visit_pat(&field.pat);
889                 }
890             }
891             _ => visit::walk_pat(self, p),
892         }
893     }
894
895     fn process_var_decl(&mut self, pat: &'l ast::Pat) {
896         // The pattern could declare multiple new vars,
897         // we must walk the pattern and collect them all.
898         let mut collector = PathCollector::new();
899         collector.visit_pat(&pat);
900         self.visit_pat(&pat);
901
902         // Process collected paths.
903         for (id, ident, _) in collector.collected_idents {
904             match self.save_ctxt.get_path_res(id) {
905                 Res::Local(hir_id) => {
906                     let id = self.tcx.hir().hir_to_node_id(hir_id);
907                     let typ = self
908                         .save_ctxt
909                         .tables
910                         .node_type_opt(hir_id)
911                         .map(|t| t.to_string())
912                         .unwrap_or_default();
913
914                     // Rust uses the id of the pattern for var lookups, so we'll use it too.
915                     if !self.span.filter_generated(ident.span) {
916                         let qualname = format!("{}${}", ident.to_string(), id);
917                         let id = id_from_node_id(id, &self.save_ctxt);
918                         let span = self.span_from_span(ident.span);
919
920                         self.dumper.dump_def(
921                             &Access { public: false, reachable: false },
922                             Def {
923                                 kind: DefKind::Local,
924                                 id,
925                                 span,
926                                 name: ident.to_string(),
927                                 qualname,
928                                 value: typ,
929                                 parent: None,
930                                 children: vec![],
931                                 decl_id: None,
932                                 docs: String::new(),
933                                 sig: None,
934                                 attributes: vec![],
935                             },
936                         );
937                     }
938                 }
939                 Res::Def(HirDefKind::Ctor(..), _)
940                 | Res::Def(HirDefKind::Const, _)
941                 | Res::Def(HirDefKind::AssocConst, _)
942                 | Res::Def(HirDefKind::Struct, _)
943                 | Res::Def(HirDefKind::Variant, _)
944                 | Res::Def(HirDefKind::TyAlias, _)
945                 | Res::Def(HirDefKind::AssocTy, _)
946                 | Res::SelfTy(..) => {
947                     self.dump_path_ref(id, &ast::Path::from_ident(ident));
948                 }
949                 def => {
950                     error!("unexpected definition kind when processing collected idents: {:?}", def)
951                 }
952             }
953         }
954
955         for (id, ref path) in collector.collected_paths {
956             self.process_path(id, path);
957         }
958     }
959
960     /// Extracts macro use and definition information from the AST node defined
961     /// by the given NodeId, using the expansion information from the node's
962     /// span.
963     ///
964     /// If the span is not macro-generated, do nothing, else use callee and
965     /// callsite spans to record macro definition and use data, using the
966     /// mac_uses and mac_defs sets to prevent multiples.
967     fn process_macro_use(&mut self, _span: Span) {
968         // FIXME if we're not dumping the defs (see below), there is no point
969         // dumping refs either.
970         // let source_span = span.source_callsite();
971         // if !self.macro_calls.insert(source_span) {
972         //     return;
973         // }
974
975         // let data = match self.save_ctxt.get_macro_use_data(span) {
976         //     None => return,
977         //     Some(data) => data,
978         // };
979
980         // self.dumper.macro_use(data);
981
982         // FIXME write the macro def
983         // let mut hasher = DefaultHasher::new();
984         // data.callee_span.hash(&mut hasher);
985         // let hash = hasher.finish();
986         // let qualname = format!("{}::{}", data.name, hash);
987         // Don't write macro definition for imported macros
988         // if !self.mac_defs.contains(&data.callee_span)
989         //     && !data.imported {
990         //     self.mac_defs.insert(data.callee_span);
991         //     if let Some(sub_span) = self.span.span_for_macro_def_name(data.callee_span) {
992         //         self.dumper.macro_data(MacroData {
993         //             span: sub_span,
994         //             name: data.name.clone(),
995         //             qualname: qualname.clone(),
996         //             // FIXME where do macro docs come from?
997         //             docs: String::new(),
998         //         }.lower(self.tcx));
999         //     }
1000         // }
1001     }
1002
1003     fn process_trait_item(&mut self, trait_item: &'l ast::AssocItem, trait_id: DefId) {
1004         self.process_macro_use(trait_item.span);
1005         let vis_span = trait_item.span.shrink_to_lo();
1006         match trait_item.kind {
1007             ast::AssocItemKind::Const(ref ty, ref expr) => {
1008                 self.process_assoc_const(
1009                     trait_item.id,
1010                     trait_item.ident,
1011                     &ty,
1012                     expr.as_ref().map(|e| &**e),
1013                     trait_id,
1014                     respan(vis_span, ast::VisibilityKind::Public),
1015                     &trait_item.attrs,
1016                 );
1017             }
1018             ast::AssocItemKind::Fn(ref sig, ref generics, ref body) => {
1019                 self.process_method(
1020                     sig,
1021                     body.as_ref().map(|x| &**x),
1022                     trait_item.id,
1023                     trait_item.ident,
1024                     generics,
1025                     respan(vis_span, ast::VisibilityKind::Public),
1026                     trait_item.span,
1027                 );
1028             }
1029             ast::AssocItemKind::TyAlias(_, ref bounds, ref default_ty) => {
1030                 // FIXME do something with _bounds (for type refs)
1031                 let name = trait_item.ident.name.to_string();
1032                 let qualname = format!(
1033                     "::{}",
1034                     self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(trait_item.id))
1035                 );
1036
1037                 if !self.span.filter_generated(trait_item.ident.span) {
1038                     let span = self.span_from_span(trait_item.ident.span);
1039                     let id = id_from_node_id(trait_item.id, &self.save_ctxt);
1040
1041                     self.dumper.dump_def(
1042                         &Access { public: true, reachable: true },
1043                         Def {
1044                             kind: DefKind::Type,
1045                             id,
1046                             span,
1047                             name,
1048                             qualname,
1049                             value: self.span.snippet(trait_item.span),
1050                             parent: Some(id_from_def_id(trait_id)),
1051                             children: vec![],
1052                             decl_id: None,
1053                             docs: self.save_ctxt.docs_for_attrs(&trait_item.attrs),
1054                             sig: sig::assoc_type_signature(
1055                                 trait_item.id,
1056                                 trait_item.ident,
1057                                 Some(bounds),
1058                                 default_ty.as_ref().map(|ty| &**ty),
1059                                 &self.save_ctxt,
1060                             ),
1061                             attributes: lower_attributes(trait_item.attrs.clone(), &self.save_ctxt),
1062                         },
1063                     );
1064                 }
1065
1066                 if let &Some(ref default_ty) = default_ty {
1067                     self.visit_ty(default_ty)
1068                 }
1069             }
1070             ast::AssocItemKind::Macro(_) => {}
1071         }
1072     }
1073
1074     fn process_impl_item(&mut self, impl_item: &'l ast::AssocItem, impl_id: DefId) {
1075         self.process_macro_use(impl_item.span);
1076         match impl_item.kind {
1077             ast::AssocItemKind::Const(ref ty, ref expr) => {
1078                 self.process_assoc_const(
1079                     impl_item.id,
1080                     impl_item.ident,
1081                     &ty,
1082                     expr.as_deref(),
1083                     impl_id,
1084                     impl_item.vis.clone(),
1085                     &impl_item.attrs,
1086                 );
1087             }
1088             ast::AssocItemKind::Fn(ref sig, ref generics, ref body) => {
1089                 self.process_method(
1090                     sig,
1091                     body.as_deref(),
1092                     impl_item.id,
1093                     impl_item.ident,
1094                     generics,
1095                     impl_item.vis.clone(),
1096                     impl_item.span,
1097                 );
1098             }
1099             ast::AssocItemKind::TyAlias(_, _, None) => {}
1100             ast::AssocItemKind::TyAlias(_, _, Some(ref ty)) => {
1101                 // FIXME: uses of the assoc type should ideally point to this
1102                 // 'def' and the name here should be a ref to the def in the
1103                 // trait.
1104                 self.visit_ty(ty)
1105             }
1106             ast::AssocItemKind::Macro(_) => {}
1107         }
1108     }
1109
1110     /// Dumps imports in a use tree recursively.
1111     ///
1112     /// A use tree is an import that may contain nested braces (RFC 2128). The `use_tree` parameter
1113     /// is the current use tree under scrutiny, while `id` and `prefix` are its corresponding node
1114     /// ID and path. `root_item` is the topmost use tree in the hierarchy.
1115     ///
1116     /// If `use_tree` is a simple or glob import, it is dumped into the analysis data. Otherwise,
1117     /// each child use tree is dumped recursively.
1118     fn process_use_tree(
1119         &mut self,
1120         use_tree: &'l ast::UseTree,
1121         id: NodeId,
1122         root_item: &'l ast::Item,
1123         prefix: &ast::Path,
1124     ) {
1125         let path = &use_tree.prefix;
1126
1127         // The access is calculated using the current tree ID, but with the root tree's visibility
1128         // (since nested trees don't have their own visibility).
1129         let hir_id = self.tcx.hir().node_to_hir_id(id);
1130         let access = access_from!(self.save_ctxt, root_item, hir_id);
1131
1132         // The parent `DefId` of a given use tree is always the enclosing item.
1133         let parent = self
1134             .save_ctxt
1135             .tcx
1136             .hir()
1137             .opt_local_def_id_from_node_id(id)
1138             .and_then(|id| self.save_ctxt.tcx.parent(id))
1139             .map(id_from_def_id);
1140
1141         match use_tree.kind {
1142             ast::UseTreeKind::Simple(alias, ..) => {
1143                 let ident = use_tree.ident();
1144                 let path = ast::Path {
1145                     segments: prefix.segments.iter().chain(path.segments.iter()).cloned().collect(),
1146                     span: path.span,
1147                 };
1148
1149                 let sub_span = path.segments.last().unwrap().ident.span;
1150                 if !self.span.filter_generated(sub_span) {
1151                     let ref_id = self.lookup_def_id(id).map(|id| id_from_def_id(id));
1152                     let alias_span = alias.map(|i| self.span_from_span(i.span));
1153                     let span = self.span_from_span(sub_span);
1154                     self.dumper.import(
1155                         &access,
1156                         Import {
1157                             kind: ImportKind::Use,
1158                             ref_id,
1159                             span,
1160                             alias_span,
1161                             name: ident.to_string(),
1162                             value: String::new(),
1163                             parent,
1164                         },
1165                     );
1166                     self.write_sub_paths_truncated(&path);
1167                 }
1168             }
1169             ast::UseTreeKind::Glob => {
1170                 let path = ast::Path {
1171                     segments: prefix.segments.iter().chain(path.segments.iter()).cloned().collect(),
1172                     span: path.span,
1173                 };
1174
1175                 // Make a comma-separated list of names of imported modules.
1176                 let def_id = self.tcx.hir().local_def_id_from_node_id(id);
1177                 let names = self.tcx.names_imported_by_glob_use(def_id);
1178                 let names: Vec<_> = names.iter().map(|n| n.to_string()).collect();
1179
1180                 // Otherwise it's a span with wrong macro expansion info, which
1181                 // we don't want to track anyway, since it's probably macro-internal `use`
1182                 if let Some(sub_span) =
1183                     self.span.sub_span_of_token(use_tree.span, token::BinOp(token::Star))
1184                 {
1185                     if !self.span.filter_generated(use_tree.span) {
1186                         let span = self.span_from_span(sub_span);
1187
1188                         self.dumper.import(
1189                             &access,
1190                             Import {
1191                                 kind: ImportKind::GlobUse,
1192                                 ref_id: None,
1193                                 span,
1194                                 alias_span: None,
1195                                 name: "*".to_owned(),
1196                                 value: names.join(", "),
1197                                 parent,
1198                             },
1199                         );
1200                         self.write_sub_paths(&path);
1201                     }
1202                 }
1203             }
1204             ast::UseTreeKind::Nested(ref nested_items) => {
1205                 let prefix = ast::Path {
1206                     segments: prefix.segments.iter().chain(path.segments.iter()).cloned().collect(),
1207                     span: path.span,
1208                 };
1209                 for &(ref tree, id) in nested_items {
1210                     self.process_use_tree(tree, id, root_item, &prefix);
1211                 }
1212             }
1213         }
1214     }
1215
1216     fn process_bounds(&mut self, bounds: &'l ast::GenericBounds) {
1217         for bound in bounds {
1218             if let ast::GenericBound::Trait(ref trait_ref, _) = *bound {
1219                 self.process_path(trait_ref.trait_ref.ref_id, &trait_ref.trait_ref.path)
1220             }
1221         }
1222     }
1223 }
1224
1225 impl<'l, 'tcx> Visitor<'l> for DumpVisitor<'l, 'tcx> {
1226     fn visit_mod(&mut self, m: &'l ast::Mod, span: Span, attrs: &[ast::Attribute], id: NodeId) {
1227         // Since we handle explicit modules ourselves in visit_item, this should
1228         // only get called for the root module of a crate.
1229         assert_eq!(id, ast::CRATE_NODE_ID);
1230
1231         let qualname =
1232             format!("::{}", self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(id)));
1233
1234         let cm = self.tcx.sess.source_map();
1235         let filename = cm.span_to_filename(span);
1236         let data_id = id_from_node_id(id, &self.save_ctxt);
1237         let children = m.items.iter().map(|i| id_from_node_id(i.id, &self.save_ctxt)).collect();
1238         let span = self.span_from_span(span);
1239
1240         self.dumper.dump_def(
1241             &Access { public: true, reachable: true },
1242             Def {
1243                 kind: DefKind::Mod,
1244                 id: data_id,
1245                 name: String::new(),
1246                 qualname,
1247                 span,
1248                 value: filename.to_string(),
1249                 children,
1250                 parent: None,
1251                 decl_id: None,
1252                 docs: self.save_ctxt.docs_for_attrs(attrs),
1253                 sig: None,
1254                 attributes: lower_attributes(attrs.to_owned(), &self.save_ctxt),
1255             },
1256         );
1257         visit::walk_mod(self, m);
1258     }
1259
1260     fn visit_item(&mut self, item: &'l ast::Item) {
1261         use syntax::ast::ItemKind::*;
1262         self.process_macro_use(item.span);
1263         match item.kind {
1264             Use(ref use_tree) => {
1265                 let prefix = ast::Path { segments: vec![], span: DUMMY_SP };
1266                 self.process_use_tree(use_tree, item.id, item, &prefix);
1267             }
1268             ExternCrate(_) => {
1269                 let name_span = item.ident.span;
1270                 if !self.span.filter_generated(name_span) {
1271                     let span = self.span_from_span(name_span);
1272                     let parent = self
1273                         .save_ctxt
1274                         .tcx
1275                         .hir()
1276                         .opt_local_def_id_from_node_id(item.id)
1277                         .and_then(|id| self.save_ctxt.tcx.parent(id))
1278                         .map(id_from_def_id);
1279                     self.dumper.import(
1280                         &Access { public: false, reachable: false },
1281                         Import {
1282                             kind: ImportKind::ExternCrate,
1283                             ref_id: None,
1284                             span,
1285                             alias_span: None,
1286                             name: item.ident.to_string(),
1287                             value: String::new(),
1288                             parent,
1289                         },
1290                     );
1291                 }
1292             }
1293             Fn(ref sig, ref ty_params, ref body) => {
1294                 self.process_fn(item, &sig.decl, &sig.header, ty_params, body.as_deref())
1295             }
1296             Static(ref typ, _, ref e) => self.process_static_or_const_item(item, typ, e.as_deref()),
1297             Const(ref typ, ref e) => self.process_static_or_const_item(item, typ, e.as_deref()),
1298             Struct(ref def, ref ty_params) | Union(ref def, ref ty_params) => {
1299                 self.process_struct(item, def, ty_params)
1300             }
1301             Enum(ref def, ref ty_params) => self.process_enum(item, def, ty_params),
1302             Impl { ref generics, ref of_trait, ref self_ty, ref items, .. } => {
1303                 self.process_impl(item, generics, of_trait, &self_ty, items)
1304             }
1305             Trait(_, _, ref generics, ref trait_refs, ref methods) => {
1306                 self.process_trait(item, generics, trait_refs, methods)
1307             }
1308             Mod(ref m) => {
1309                 self.process_mod(item);
1310                 visit::walk_mod(self, m);
1311             }
1312             TyAlias(ref ty, ref ty_params) => {
1313                 let qualname = format!(
1314                     "::{}",
1315                     self.tcx.def_path_str(self.tcx.hir().local_def_id_from_node_id(item.id))
1316                 );
1317                 let value = ty_to_string(&ty);
1318                 if !self.span.filter_generated(item.ident.span) {
1319                     let span = self.span_from_span(item.ident.span);
1320                     let id = id_from_node_id(item.id, &self.save_ctxt);
1321                     let hir_id = self.tcx.hir().node_to_hir_id(item.id);
1322
1323                     self.dumper.dump_def(
1324                         &access_from!(self.save_ctxt, item, hir_id),
1325                         Def {
1326                             kind: DefKind::Type,
1327                             id,
1328                             span,
1329                             name: item.ident.to_string(),
1330                             qualname: qualname.clone(),
1331                             value,
1332                             parent: None,
1333                             children: vec![],
1334                             decl_id: None,
1335                             docs: self.save_ctxt.docs_for_attrs(&item.attrs),
1336                             sig: sig::item_signature(item, &self.save_ctxt),
1337                             attributes: lower_attributes(item.attrs.clone(), &self.save_ctxt),
1338                         },
1339                     );
1340                 }
1341
1342                 self.visit_ty(&ty);
1343                 self.process_generic_params(ty_params, &qualname, item.id);
1344             }
1345             Mac(_) => (),
1346             _ => visit::walk_item(self, item),
1347         }
1348     }
1349
1350     fn visit_generics(&mut self, generics: &'l ast::Generics) {
1351         for param in &generics.params {
1352             match param.kind {
1353                 ast::GenericParamKind::Lifetime { .. } => {}
1354                 ast::GenericParamKind::Type { ref default, .. } => {
1355                     self.process_bounds(&param.bounds);
1356                     if let Some(ref ty) = default {
1357                         self.visit_ty(&ty);
1358                     }
1359                 }
1360                 ast::GenericParamKind::Const { ref ty } => {
1361                     self.process_bounds(&param.bounds);
1362                     self.visit_ty(&ty);
1363                 }
1364             }
1365         }
1366         for pred in &generics.where_clause.predicates {
1367             if let ast::WherePredicate::BoundPredicate(ref wbp) = *pred {
1368                 self.process_bounds(&wbp.bounds);
1369                 self.visit_ty(&wbp.bounded_ty);
1370             }
1371         }
1372     }
1373
1374     fn visit_ty(&mut self, t: &'l ast::Ty) {
1375         self.process_macro_use(t.span);
1376         match t.kind {
1377             ast::TyKind::Path(_, ref path) => {
1378                 if generated_code(t.span) {
1379                     return;
1380                 }
1381
1382                 if let Some(id) = self.lookup_def_id(t.id) {
1383                     let sub_span = path.segments.last().unwrap().ident.span;
1384                     let span = self.span_from_span(sub_span);
1385                     self.dumper.dump_ref(Ref {
1386                         kind: RefKind::Type,
1387                         span,
1388                         ref_id: id_from_def_id(id),
1389                     });
1390                 }
1391
1392                 self.write_sub_paths_truncated(path);
1393                 visit::walk_path(self, path);
1394             }
1395             ast::TyKind::Array(ref element, ref length) => {
1396                 self.visit_ty(element);
1397                 self.nest_tables(length.id, |v| v.visit_expr(&length.value));
1398             }
1399             ast::TyKind::ImplTrait(id, ref bounds) => {
1400                 // FIXME: As of writing, the opaque type lowering introduces
1401                 // another DefPath scope/segment (used to declare the resulting
1402                 // opaque type item).
1403                 // However, the synthetic scope does *not* have associated
1404                 // typeck tables, which means we can't nest it and we fire an
1405                 // assertion when resolving the qualified type paths in trait
1406                 // bounds...
1407                 // This will panic if called on return type `impl Trait`, which
1408                 // we guard against in `process_fn`.
1409                 self.nest_tables(id, |v| v.process_bounds(bounds));
1410             }
1411             _ => visit::walk_ty(self, t),
1412         }
1413     }
1414
1415     fn visit_expr(&mut self, ex: &'l ast::Expr) {
1416         debug!("visit_expr {:?}", ex.kind);
1417         self.process_macro_use(ex.span);
1418         match ex.kind {
1419             ast::ExprKind::Struct(ref path, ref fields, ref base) => {
1420                 let expr_hir_id = self.save_ctxt.tcx.hir().node_to_hir_id(ex.id);
1421                 let hir_expr = self.save_ctxt.tcx.hir().expect_expr(expr_hir_id);
1422                 let adt = match self.save_ctxt.tables.expr_ty_opt(&hir_expr) {
1423                     Some(ty) if ty.ty_adt_def().is_some() => ty.ty_adt_def().unwrap(),
1424                     _ => {
1425                         visit::walk_expr(self, ex);
1426                         return;
1427                     }
1428                 };
1429                 let node_id = self.save_ctxt.tcx.hir().hir_to_node_id(hir_expr.hir_id);
1430                 let res = self.save_ctxt.get_path_res(node_id);
1431                 self.process_struct_lit(ex, path, fields, adt.variant_of_res(res), base)
1432             }
1433             ast::ExprKind::MethodCall(ref seg, ref args) => self.process_method_call(ex, seg, args),
1434             ast::ExprKind::Field(ref sub_ex, _) => {
1435                 self.visit_expr(&sub_ex);
1436
1437                 if let Some(field_data) = self.save_ctxt.get_expr_data(ex) {
1438                     down_cast_data!(field_data, RefData, ex.span);
1439                     if !generated_code(ex.span) {
1440                         self.dumper.dump_ref(field_data);
1441                     }
1442                 }
1443             }
1444             ast::ExprKind::Closure(_, _, _, ref decl, ref body, _fn_decl_span) => {
1445                 let id = format!("${}", ex.id);
1446
1447                 // walk arg and return types
1448                 for arg in &decl.inputs {
1449                     self.visit_ty(&arg.ty);
1450                 }
1451
1452                 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1453                     self.visit_ty(&ret_ty);
1454                 }
1455
1456                 // walk the body
1457                 self.nest_tables(ex.id, |v| {
1458                     v.process_formals(&decl.inputs, &id);
1459                     v.visit_expr(body)
1460                 });
1461             }
1462             ast::ExprKind::ForLoop(ref pattern, ref subexpression, ref block, _) => {
1463                 self.process_var_decl(pattern);
1464                 debug!("for loop, walk sub-expr: {:?}", subexpression.kind);
1465                 self.visit_expr(subexpression);
1466                 visit::walk_block(self, block);
1467             }
1468             ast::ExprKind::Let(ref pat, ref scrutinee) => {
1469                 self.process_var_decl(pat);
1470                 self.visit_expr(scrutinee);
1471             }
1472             ast::ExprKind::Repeat(ref element, ref count) => {
1473                 self.visit_expr(element);
1474                 self.nest_tables(count.id, |v| v.visit_expr(&count.value));
1475             }
1476             // In particular, we take this branch for call and path expressions,
1477             // where we'll index the idents involved just by continuing to walk.
1478             _ => visit::walk_expr(self, ex),
1479         }
1480     }
1481
1482     fn visit_pat(&mut self, p: &'l ast::Pat) {
1483         self.process_macro_use(p.span);
1484         self.process_pat(p);
1485     }
1486
1487     fn visit_arm(&mut self, arm: &'l ast::Arm) {
1488         self.process_var_decl(&arm.pat);
1489         if let Some(expr) = &arm.guard {
1490             self.visit_expr(expr);
1491         }
1492         self.visit_expr(&arm.body);
1493     }
1494
1495     fn visit_path(&mut self, p: &'l ast::Path, id: NodeId) {
1496         self.process_path(id, p);
1497     }
1498
1499     fn visit_stmt(&mut self, s: &'l ast::Stmt) {
1500         self.process_macro_use(s.span);
1501         visit::walk_stmt(self, s)
1502     }
1503
1504     fn visit_local(&mut self, l: &'l ast::Local) {
1505         self.process_macro_use(l.span);
1506         self.process_var_decl(&l.pat);
1507
1508         // Just walk the initialiser and type (don't want to walk the pattern again).
1509         walk_list!(self, visit_ty, &l.ty);
1510         walk_list!(self, visit_expr, &l.init);
1511     }
1512
1513     fn visit_foreign_item(&mut self, item: &'l ast::ForeignItem) {
1514         let hir_id = self.tcx.hir().node_to_hir_id(item.id);
1515         let access = access_from!(self.save_ctxt, item, hir_id);
1516
1517         match item.kind {
1518             ast::ForeignItemKind::Fn(ref sig, ref generics, _) => {
1519                 let decl = &sig.decl;
1520                 if let Some(fn_data) = self.save_ctxt.get_extern_item_data(item) {
1521                     down_cast_data!(fn_data, DefData, item.span);
1522
1523                     self.process_generic_params(generics, &fn_data.qualname, item.id);
1524                     self.dumper.dump_def(&access, fn_data);
1525                 }
1526
1527                 for arg in &decl.inputs {
1528                     self.visit_ty(&arg.ty);
1529                 }
1530
1531                 if let ast::FunctionRetTy::Ty(ref ret_ty) = decl.output {
1532                     self.visit_ty(&ret_ty);
1533                 }
1534             }
1535             ast::ForeignItemKind::Static(ref ty, _, _) => {
1536                 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1537                     down_cast_data!(var_data, DefData, item.span);
1538                     self.dumper.dump_def(&access, var_data);
1539                 }
1540
1541                 self.visit_ty(ty);
1542             }
1543             ast::ForeignItemKind::TyAlias(..) => {
1544                 if let Some(var_data) = self.save_ctxt.get_extern_item_data(item) {
1545                     down_cast_data!(var_data, DefData, item.span);
1546                     self.dumper.dump_def(&access, var_data);
1547                 }
1548             }
1549             ast::ForeignItemKind::Macro(..) => {}
1550         }
1551     }
1552 }