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