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