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