]> git.lizzy.rs Git - rust.git/blob - src/librustc_save_analysis/lib.rs
Rollup merge of #40521 - TimNN:panic-free-shift, r=alexcrichton
[rust.git] / src / librustc_save_analysis / lib.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 #![crate_name = "rustc_save_analysis"]
12 #![unstable(feature = "rustc_private", issue = "27812")]
13 #![crate_type = "dylib"]
14 #![crate_type = "rlib"]
15 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
16       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
17       html_root_url = "https://doc.rust-lang.org/nightly/")]
18 #![deny(warnings)]
19
20 #![feature(custom_attribute)]
21 #![allow(unused_attributes)]
22 #![feature(rustc_private)]
23 #![feature(staged_api)]
24
25 #[macro_use] extern crate rustc;
26
27 #[macro_use] extern crate log;
28 #[macro_use] extern crate syntax;
29 extern crate serialize as rustc_serialize;
30 extern crate syntax_pos;
31
32
33 mod csv_dumper;
34 mod json_api_dumper;
35 mod json_dumper;
36 mod data;
37 mod dump;
38 mod dump_visitor;
39 pub mod external_data;
40 #[macro_use]
41 pub mod span_utils;
42
43 use rustc::hir;
44 use rustc::hir::def::Def;
45 use rustc::hir::map::Node;
46 use rustc::hir::def_id::DefId;
47 use rustc::session::config::CrateType::CrateTypeExecutable;
48 use rustc::ty::{self, TyCtxt};
49
50 use std::env;
51 use std::fs::File;
52 use std::path::{Path, PathBuf};
53
54 use syntax::ast::{self, NodeId, PatKind, Attribute, CRATE_NODE_ID};
55 use syntax::parse::lexer::comments::strip_doc_comment_decoration;
56 use syntax::parse::token;
57 use syntax::symbol::keywords;
58 use syntax::visit::{self, Visitor};
59 use syntax::print::pprust::{ty_to_string, arg_to_string};
60 use syntax::codemap::MacroAttribute;
61 use syntax_pos::*;
62
63 pub use self::csv_dumper::CsvDumper;
64 pub use self::json_api_dumper::JsonApiDumper;
65 pub use self::json_dumper::JsonDumper;
66 pub use self::data::*;
67 pub use self::external_data::make_def_id;
68 pub use self::dump::Dump;
69 pub use self::dump_visitor::DumpVisitor;
70 use self::span_utils::SpanUtils;
71
72 // FIXME this is legacy code and should be removed
73 pub mod recorder {
74     pub use self::Row::*;
75
76     #[derive(Copy, Clone, Debug, Eq, PartialEq)]
77     pub enum Row {
78         TypeRef,
79         ModRef,
80         VarRef,
81         FnRef,
82     }
83 }
84
85 pub struct SaveContext<'l, 'tcx: 'l> {
86     tcx: TyCtxt<'l, 'tcx, 'tcx>,
87     tables: &'l ty::TypeckTables<'tcx>,
88     analysis: &'l ty::CrateAnalysis,
89     span_utils: SpanUtils<'tcx>,
90 }
91
92 macro_rules! option_try(
93     ($e:expr) => (match $e { Some(e) => e, None => return None })
94 );
95
96 impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
97     // List external crates used by the current crate.
98     pub fn get_external_crates(&self) -> Vec<CrateData> {
99         let mut result = Vec::new();
100
101         for n in self.tcx.sess.cstore.crates() {
102             let span = match self.tcx.sess.cstore.extern_crate(n) {
103                 Some(ref c) => c.span,
104                 None => {
105                     debug!("Skipping crate {}, no data", n);
106                     continue;
107                 }
108             };
109             result.push(CrateData {
110                 name: self.tcx.sess.cstore.crate_name(n).to_string(),
111                 number: n.as_u32(),
112                 span: span,
113             });
114         }
115
116         result
117     }
118
119     pub fn get_item_data(&self, item: &ast::Item) -> Option<Data> {
120         match item.node {
121             ast::ItemKind::Fn(ref decl, .., ref generics, _) => {
122                 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
123                 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Fn);
124                 filter!(self.span_utils, sub_span, item.span, None);
125
126
127                 Some(Data::FunctionData(FunctionData {
128                     id: item.id,
129                     name: item.ident.to_string(),
130                     qualname: qualname,
131                     declaration: None,
132                     span: sub_span.unwrap(),
133                     scope: self.enclosing_scope(item.id),
134                     value: make_signature(decl, generics),
135                     visibility: From::from(&item.vis),
136                     parent: None,
137                     docs: docs_for_attrs(&item.attrs),
138                     sig: self.sig_base(item),
139                     attributes: item.attrs.clone(),
140                 }))
141             }
142             ast::ItemKind::Static(ref typ, mt, ref expr) => {
143                 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
144
145                 // If the variable is immutable, save the initialising expression.
146                 let (value, keyword) = match mt {
147                     ast::Mutability::Mutable => (String::from("<mutable>"), keywords::Mut),
148                     ast::Mutability::Immutable => {
149                         (self.span_utils.snippet(expr.span), keywords::Static)
150                     },
151                 };
152
153                 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keyword);
154                 filter!(self.span_utils, sub_span, item.span, None);
155                 Some(Data::VariableData(VariableData {
156                     id: item.id,
157                     kind: VariableKind::Static,
158                     name: item.ident.to_string(),
159                     qualname: qualname,
160                     span: sub_span.unwrap(),
161                     scope: self.enclosing_scope(item.id),
162                     parent: None,
163                     value: value,
164                     type_value: ty_to_string(&typ),
165                     visibility: From::from(&item.vis),
166                     docs: docs_for_attrs(&item.attrs),
167                     sig: Some(self.sig_base(item)),
168                     attributes: item.attrs.clone(),
169                 }))
170             }
171             ast::ItemKind::Const(ref typ, ref expr) => {
172                 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
173                 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Const);
174                 filter!(self.span_utils, sub_span, item.span, None);
175                 Some(Data::VariableData(VariableData {
176                     id: item.id,
177                     kind: VariableKind::Const,
178                     name: item.ident.to_string(),
179                     qualname: qualname,
180                     span: sub_span.unwrap(),
181                     scope: self.enclosing_scope(item.id),
182                     parent: None,
183                     value: self.span_utils.snippet(expr.span),
184                     type_value: ty_to_string(&typ),
185                     visibility: From::from(&item.vis),
186                     docs: docs_for_attrs(&item.attrs),
187                     sig: Some(self.sig_base(item)),
188                     attributes: item.attrs.clone(),
189                 }))
190             }
191             ast::ItemKind::Mod(ref m) => {
192                 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
193
194                 let cm = self.tcx.sess.codemap();
195                 let filename = cm.span_to_filename(m.inner);
196
197                 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Mod);
198                 filter!(self.span_utils, sub_span, item.span, None);
199
200                 Some(Data::ModData(ModData {
201                     id: item.id,
202                     name: item.ident.to_string(),
203                     qualname: qualname,
204                     span: sub_span.unwrap(),
205                     scope: self.enclosing_scope(item.id),
206                     filename: filename,
207                     items: m.items.iter().map(|i| i.id).collect(),
208                     visibility: From::from(&item.vis),
209                     docs: docs_for_attrs(&item.attrs),
210                     sig: self.sig_base(item),
211                     attributes: item.attrs.clone(),
212                 }))
213             }
214             ast::ItemKind::Enum(ref def, _) => {
215                 let name = item.ident.to_string();
216                 let qualname = format!("::{}", self.tcx.node_path_str(item.id));
217                 let sub_span = self.span_utils.sub_span_after_keyword(item.span, keywords::Enum);
218                 filter!(self.span_utils, sub_span, item.span, None);
219                 let variants_str = def.variants.iter()
220                                       .map(|v| v.node.name.to_string())
221                                       .collect::<Vec<_>>()
222                                       .join(", ");
223                 let val = format!("{}::{{{}}}", name, variants_str);
224                 Some(Data::EnumData(EnumData {
225                     id: item.id,
226                     name: name,
227                     value: val,
228                     span: sub_span.unwrap(),
229                     qualname: qualname,
230                     scope: self.enclosing_scope(item.id),
231                     variants: def.variants.iter().map(|v| v.node.data.id()).collect(),
232                     visibility: From::from(&item.vis),
233                     docs: docs_for_attrs(&item.attrs),
234                     sig: self.sig_base(item),
235                     attributes: item.attrs.clone(),
236                 }))
237             }
238             ast::ItemKind::Impl(.., ref trait_ref, ref typ, _) => {
239                 let mut type_data = None;
240                 let sub_span;
241
242                 let parent = self.enclosing_scope(item.id);
243
244                 match typ.node {
245                     // Common case impl for a struct or something basic.
246                     ast::TyKind::Path(None, ref path) => {
247                         if generated_code(path.span) {
248                             return None;
249                         }
250                         sub_span = self.span_utils.sub_span_for_type_name(path.span);
251                         type_data = self.lookup_ref_id(typ.id).map(|id| {
252                             TypeRefData {
253                                 span: sub_span.unwrap(),
254                                 scope: parent,
255                                 ref_id: Some(id),
256                                 qualname: String::new() // FIXME: generate the real qualname
257                             }
258                         });
259                     }
260                     _ => {
261                         // Less useful case, impl for a compound type.
262                         let span = typ.span;
263                         sub_span = self.span_utils.sub_span_for_type_name(span).or(Some(span));
264                     }
265                 }
266
267                 let trait_data = trait_ref.as_ref()
268                                           .and_then(|tr| self.get_trait_ref_data(tr, parent));
269
270                 filter!(self.span_utils, sub_span, typ.span, None);
271                 Some(Data::ImplData(ImplData2 {
272                     id: item.id,
273                     span: sub_span.unwrap(),
274                     scope: parent,
275                     trait_ref: trait_data,
276                     self_ref: type_data,
277                 }))
278             }
279             _ => {
280                 // FIXME
281                 bug!();
282             }
283         }
284     }
285
286     pub fn get_field_data(&self,
287                           field: &ast::StructField,
288                           scope: NodeId)
289                           -> Option<VariableData> {
290         if let Some(ident) = field.ident {
291             let name = ident.to_string();
292             let qualname = format!("::{}::{}", self.tcx.node_path_str(scope), ident);
293             let sub_span = self.span_utils.sub_span_before_token(field.span, token::Colon);
294             filter!(self.span_utils, sub_span, field.span, None);
295             let def_id = self.tcx.hir.local_def_id(field.id);
296             let typ = self.tcx.item_type(def_id).to_string();
297
298             let span = field.span;
299             let text = self.span_utils.snippet(field.span);
300             let ident_start = text.find(&name).unwrap();
301             let ident_end = ident_start + name.len();
302             let sig = Signature {
303                 span: span,
304                 text: text,
305                 ident_start: ident_start,
306                 ident_end: ident_end,
307                 defs: vec![],
308                 refs: vec![],
309             };
310             Some(VariableData {
311                 id: field.id,
312                 kind: VariableKind::Field,
313                 name: name,
314                 qualname: qualname,
315                 span: sub_span.unwrap(),
316                 scope: scope,
317                 parent: Some(make_def_id(scope, &self.tcx.hir)),
318                 value: "".to_owned(),
319                 type_value: typ,
320                 visibility: From::from(&field.vis),
321                 docs: docs_for_attrs(&field.attrs),
322                 sig: Some(sig),
323                 attributes: field.attrs.clone(),
324             })
325         } else {
326             None
327         }
328     }
329
330     // FIXME would be nice to take a MethodItem here, but the ast provides both
331     // trait and impl flavours, so the caller must do the disassembly.
332     pub fn get_method_data(&self, id: ast::NodeId,
333                            name: ast::Name, span: Span) -> Option<FunctionData> {
334         // The qualname for a method is the trait name or name of the struct in an impl in
335         // which the method is declared in, followed by the method's name.
336         let (qualname, parent_scope, decl_id, vis, docs, attributes) =
337           match self.tcx.impl_of_method(self.tcx.hir.local_def_id(id)) {
338             Some(impl_id) => match self.tcx.hir.get_if_local(impl_id) {
339                 Some(Node::NodeItem(item)) => {
340                     match item.node {
341                         hir::ItemImpl(.., ref ty, _) => {
342                             let mut result = String::from("<");
343                             result.push_str(&self.tcx.hir.node_to_pretty_string(ty.id));
344
345                             let trait_id = self.tcx.trait_id_of_impl(impl_id);
346                             let mut decl_id = None;
347                             if let Some(def_id) = trait_id {
348                                 result.push_str(" as ");
349                                 result.push_str(&self.tcx.item_path_str(def_id));
350                                 self.tcx.associated_items(def_id)
351                                     .find(|item| item.name == name)
352                                     .map(|item| decl_id = Some(item.def_id));
353                             }
354                             result.push_str(">");
355
356                             (result, trait_id, decl_id,
357                              From::from(&item.vis),
358                              docs_for_attrs(&item.attrs),
359                              item.attrs.to_vec())
360                         }
361                         _ => {
362                             span_bug!(span,
363                                       "Container {:?} for method {} not an impl?",
364                                       impl_id,
365                                       id);
366                         }
367                     }
368                 }
369                 r => {
370                     span_bug!(span,
371                               "Container {:?} for method {} is not a node item {:?}",
372                               impl_id,
373                               id,
374                               r);
375                 }
376             },
377             None => match self.tcx.trait_of_item(self.tcx.hir.local_def_id(id)) {
378                 Some(def_id) => {
379                     match self.tcx.hir.get_if_local(def_id) {
380                         Some(Node::NodeItem(item)) => {
381                             (format!("::{}", self.tcx.item_path_str(def_id)),
382                              Some(def_id), None,
383                              From::from(&item.vis),
384                              docs_for_attrs(&item.attrs),
385                              item.attrs.to_vec())
386                         }
387                         r => {
388                             span_bug!(span,
389                                       "Could not find container {:?} for \
390                                        method {}, got {:?}",
391                                       def_id,
392                                       id,
393                                       r);
394                         }
395                     }
396                 }
397                 None => {
398                     debug!("Could not find container for method {} at {:?}", id, span);
399                     // This is not necessarily a bug, if there was a compilation error, the tables
400                     // we need might not exist.
401                     return None;
402                 }
403             },
404         };
405
406         let qualname = format!("{}::{}", qualname, name);
407
408         let sub_span = self.span_utils.sub_span_after_keyword(span, keywords::Fn);
409         filter!(self.span_utils, sub_span, span, None);
410
411         let name = name.to_string();
412         let text = self.span_utils.signature_string_for_span(span);
413         let ident_start = text.find(&name).unwrap();
414         let ident_end = ident_start + name.len();
415         let sig = Signature {
416             span: span,
417             text: text,
418             ident_start: ident_start,
419             ident_end: ident_end,
420             defs: vec![],
421             refs: vec![],
422         };
423
424         Some(FunctionData {
425             id: id,
426             name: name,
427             qualname: qualname,
428             declaration: decl_id,
429             span: sub_span.unwrap(),
430             scope: self.enclosing_scope(id),
431             // FIXME you get better data here by using the visitor.
432             value: String::new(),
433             visibility: vis,
434             parent: parent_scope,
435             docs: docs,
436             sig: sig,
437             attributes: attributes,
438         })
439     }
440
441     pub fn get_trait_ref_data(&self,
442                               trait_ref: &ast::TraitRef,
443                               parent: NodeId)
444                               -> Option<TypeRefData> {
445         self.lookup_ref_id(trait_ref.ref_id).and_then(|def_id| {
446             let span = trait_ref.path.span;
447             if generated_code(span) {
448                 return None;
449             }
450             let sub_span = self.span_utils.sub_span_for_type_name(span).or(Some(span));
451             filter!(self.span_utils, sub_span, span, None);
452             Some(TypeRefData {
453                 span: sub_span.unwrap(),
454                 scope: parent,
455                 ref_id: Some(def_id),
456                 qualname: String::new() // FIXME: generate the real qualname
457             })
458         })
459     }
460
461     pub fn get_expr_data(&self, expr: &ast::Expr) -> Option<Data> {
462         let hir_node = self.tcx.hir.expect_expr(expr.id);
463         let ty = self.tables.expr_ty_adjusted_opt(&hir_node);
464         if ty.is_none() || ty.unwrap().sty == ty::TyError {
465             return None;
466         }
467         match expr.node {
468             ast::ExprKind::Field(ref sub_ex, ident) => {
469                 let hir_node = match self.tcx.hir.find(sub_ex.id) {
470                     Some(Node::NodeExpr(expr)) => expr,
471                     _ => {
472                         debug!("Missing or weird node for sub-expression {} in {:?}",
473                                sub_ex.id, expr);
474                         return None;
475                     }
476                 };
477                 match self.tables.expr_ty_adjusted(&hir_node).sty {
478                     ty::TyAdt(def, _) if !def.is_enum() => {
479                         let f = def.struct_variant().field_named(ident.node.name);
480                         let sub_span = self.span_utils.span_for_last_ident(expr.span);
481                         filter!(self.span_utils, sub_span, expr.span, None);
482                         return Some(Data::VariableRefData(VariableRefData {
483                             name: ident.node.to_string(),
484                             span: sub_span.unwrap(),
485                             scope: self.enclosing_scope(expr.id),
486                             ref_id: f.did,
487                         }));
488                     }
489                     _ => {
490                         debug!("Expected struct or union type, found {:?}", ty);
491                         None
492                     }
493                 }
494             }
495             ast::ExprKind::Struct(ref path, ..) => {
496                 match self.tables.expr_ty_adjusted(&hir_node).sty {
497                     ty::TyAdt(def, _) if !def.is_enum() => {
498                         let sub_span = self.span_utils.span_for_last_ident(path.span);
499                         filter!(self.span_utils, sub_span, path.span, None);
500                         Some(Data::TypeRefData(TypeRefData {
501                             span: sub_span.unwrap(),
502                             scope: self.enclosing_scope(expr.id),
503                             ref_id: Some(def.did),
504                             qualname: String::new() // FIXME: generate the real qualname
505                         }))
506                     }
507                     _ => {
508                         // FIXME ty could legitimately be an enum, but then we will fail
509                         // later if we try to look up the fields.
510                         debug!("expected struct or union, found {:?}", ty);
511                         None
512                     }
513                 }
514             }
515             ast::ExprKind::MethodCall(..) => {
516                 let method_call = ty::MethodCall::expr(expr.id);
517                 let method_id = self.tables.method_map[&method_call].def_id;
518                 let (def_id, decl_id) = match self.tcx.associated_item(method_id).container {
519                     ty::ImplContainer(_) => (Some(method_id), None),
520                     ty::TraitContainer(_) => (None, Some(method_id)),
521                 };
522                 let sub_span = self.span_utils.sub_span_for_meth_name(expr.span);
523                 filter!(self.span_utils, sub_span, expr.span, None);
524                 let parent = self.enclosing_scope(expr.id);
525                 Some(Data::MethodCallData(MethodCallData {
526                     span: sub_span.unwrap(),
527                     scope: parent,
528                     ref_id: def_id,
529                     decl_id: decl_id,
530                 }))
531             }
532             ast::ExprKind::Path(_, ref path) => {
533                 self.get_path_data(expr.id, path)
534             }
535             _ => {
536                 // FIXME
537                 bug!();
538             }
539         }
540     }
541
542     pub fn get_path_def(&self, id: NodeId) -> Def {
543         match self.tcx.hir.get(id) {
544             Node::NodeTraitRef(tr) => tr.path.def,
545
546             Node::NodeItem(&hir::Item { node: hir::ItemUse(ref path, _), .. }) |
547             Node::NodeVisibility(&hir::Visibility::Restricted { ref path, .. }) => path.def,
548
549             Node::NodeExpr(&hir::Expr { node: hir::ExprPath(ref qpath), .. }) |
550             Node::NodeExpr(&hir::Expr { node: hir::ExprStruct(ref qpath, ..), .. }) |
551             Node::NodePat(&hir::Pat { node: hir::PatKind::Path(ref qpath), .. }) |
552             Node::NodePat(&hir::Pat { node: hir::PatKind::Struct(ref qpath, ..), .. }) |
553             Node::NodePat(&hir::Pat { node: hir::PatKind::TupleStruct(ref qpath, ..), .. }) => {
554                 self.tables.qpath_def(qpath, id)
555             }
556
557             Node::NodeLocal(&hir::Pat { node: hir::PatKind::Binding(_, def_id, ..), .. }) => {
558                 Def::Local(def_id)
559             }
560
561             Node::NodeTy(&hir::Ty { node: hir::TyPath(ref qpath), .. }) => {
562                 match *qpath {
563                     hir::QPath::Resolved(_, ref path) => path.def,
564                     hir::QPath::TypeRelative(..) => {
565                         if let Some(ty) = self.tcx.ast_ty_to_ty_cache.borrow().get(&id) {
566                             if let ty::TyProjection(proj) = ty.sty {
567                                 for item in self.tcx.associated_items(proj.trait_ref.def_id) {
568                                     if item.kind == ty::AssociatedKind::Type {
569                                         if item.name == proj.item_name {
570                                             return Def::AssociatedTy(item.def_id);
571                                         }
572                                     }
573                                 }
574                             }
575                         }
576                         Def::Err
577                     }
578                 }
579             }
580
581             _ => Def::Err
582         }
583     }
584
585     pub fn get_path_data(&self, id: NodeId, path: &ast::Path) -> Option<Data> {
586         let def = self.get_path_def(id);
587         let sub_span = self.span_utils.span_for_last_ident(path.span);
588         filter!(self.span_utils, sub_span, path.span, None);
589         match def {
590             Def::Upvar(..) |
591             Def::Local(..) |
592             Def::Static(..) |
593             Def::Const(..) |
594             Def::AssociatedConst(..) |
595             Def::StructCtor(..) |
596             Def::VariantCtor(..) => {
597                 Some(Data::VariableRefData(VariableRefData {
598                     name: self.span_utils.snippet(sub_span.unwrap()),
599                     span: sub_span.unwrap(),
600                     scope: self.enclosing_scope(id),
601                     ref_id: def.def_id(),
602                 }))
603             }
604             Def::Struct(def_id) |
605             Def::Variant(def_id, ..) |
606             Def::Union(def_id) |
607             Def::Enum(def_id) |
608             Def::TyAlias(def_id) |
609             Def::AssociatedTy(def_id) |
610             Def::Trait(def_id) |
611             Def::TyParam(def_id) => {
612                 Some(Data::TypeRefData(TypeRefData {
613                     span: sub_span.unwrap(),
614                     ref_id: Some(def_id),
615                     scope: self.enclosing_scope(id),
616                     qualname: String::new() // FIXME: generate the real qualname
617                 }))
618             }
619             Def::Method(decl_id) => {
620                 let sub_span = self.span_utils.sub_span_for_meth_name(path.span);
621                 filter!(self.span_utils, sub_span, path.span, None);
622                 let def_id = if decl_id.is_local() {
623                     let ti = self.tcx.associated_item(decl_id);
624                     self.tcx.associated_items(ti.container.id())
625                         .find(|item| item.name == ti.name && item.defaultness.has_value())
626                         .map(|item| item.def_id)
627                 } else {
628                     None
629                 };
630                 Some(Data::MethodCallData(MethodCallData {
631                     span: sub_span.unwrap(),
632                     scope: self.enclosing_scope(id),
633                     ref_id: def_id,
634                     decl_id: Some(decl_id),
635                 }))
636             }
637             Def::Fn(def_id) => {
638                 Some(Data::FunctionCallData(FunctionCallData {
639                     ref_id: def_id,
640                     span: sub_span.unwrap(),
641                     scope: self.enclosing_scope(id),
642                 }))
643             }
644             Def::Mod(def_id) => {
645                 Some(Data::ModRefData(ModRefData {
646                     ref_id: Some(def_id),
647                     span: sub_span.unwrap(),
648                     scope: self.enclosing_scope(id),
649                     qualname: String::new() // FIXME: generate the real qualname
650                 }))
651             }
652             Def::PrimTy(..) |
653             Def::SelfTy(..) |
654             Def::Label(..) |
655             Def::Macro(..) |
656             Def::Err => None,
657         }
658     }
659
660     pub fn get_field_ref_data(&self,
661                               field_ref: &ast::Field,
662                               variant: &ty::VariantDef,
663                               parent: NodeId)
664                               -> Option<VariableRefData> {
665         let f = variant.field_named(field_ref.ident.node.name);
666         // We don't really need a sub-span here, but no harm done
667         let sub_span = self.span_utils.span_for_last_ident(field_ref.ident.span);
668         filter!(self.span_utils, sub_span, field_ref.ident.span, None);
669         Some(VariableRefData {
670             name: field_ref.ident.node.to_string(),
671             span: sub_span.unwrap(),
672             scope: parent,
673             ref_id: f.did,
674         })
675     }
676
677     /// Attempt to return MacroUseData for any AST node.
678     ///
679     /// For a given piece of AST defined by the supplied Span and NodeId,
680     /// returns None if the node is not macro-generated or the span is malformed,
681     /// else uses the expansion callsite and callee to return some MacroUseData.
682     pub fn get_macro_use_data(&self, span: Span, id: NodeId) -> Option<MacroUseData> {
683         if !generated_code(span) {
684             return None;
685         }
686         // Note we take care to use the source callsite/callee, to handle
687         // nested expansions and ensure we only generate data for source-visible
688         // macro uses.
689         let callsite = self.tcx.sess.codemap().source_callsite(span);
690         let callee = self.tcx.sess.codemap().source_callee(span);
691         let callee = option_try!(callee);
692         let callee_span = option_try!(callee.span);
693
694         // Ignore attribute macros, their spans are usually mangled
695         if let MacroAttribute(_) = callee.format {
696             return None;
697         }
698
699         // If the callee is an imported macro from an external crate, need to get
700         // the source span and name from the session, as their spans are localized
701         // when read in, and no longer correspond to the source.
702         if let Some(mac) = self.tcx.sess.imported_macro_spans.borrow().get(&callee_span) {
703             let &(ref mac_name, mac_span) = mac;
704             return Some(MacroUseData {
705                                         span: callsite,
706                                         name: mac_name.clone(),
707                                         callee_span: mac_span,
708                                         scope: self.enclosing_scope(id),
709                                         imported: true,
710                                         qualname: String::new()// FIXME: generate the real qualname
711                                     });
712         }
713
714         Some(MacroUseData {
715             span: callsite,
716             name: callee.name().to_string(),
717             callee_span: callee_span,
718             scope: self.enclosing_scope(id),
719             imported: false,
720             qualname: String::new() // FIXME: generate the real qualname
721         })
722     }
723
724     pub fn get_data_for_id(&self, _id: &NodeId) -> Data {
725         // FIXME
726         bug!();
727     }
728
729     fn lookup_ref_id(&self, ref_id: NodeId) -> Option<DefId> {
730         match self.get_path_def(ref_id) {
731             Def::PrimTy(_) | Def::SelfTy(..) | Def::Err => None,
732             def => Some(def.def_id()),
733         }
734     }
735
736     fn sig_base(&self, item: &ast::Item) -> Signature {
737         let text = self.span_utils.signature_string_for_span(item.span);
738         let name = item.ident.to_string();
739         let ident_start = text.find(&name).expect("Name not in signature?");
740         let ident_end = ident_start + name.len();
741         Signature {
742             span: mk_sp(item.span.lo, item.span.lo + BytePos(text.len() as u32)),
743             text: text,
744             ident_start: ident_start,
745             ident_end: ident_end,
746             defs: vec![],
747             refs: vec![],
748         }
749     }
750
751     #[inline]
752     pub fn enclosing_scope(&self, id: NodeId) -> NodeId {
753         self.tcx.hir.get_enclosing_scope(id).unwrap_or(CRATE_NODE_ID)
754     }
755 }
756
757 fn make_signature(decl: &ast::FnDecl, generics: &ast::Generics) -> String {
758     let mut sig = "fn ".to_owned();
759     if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
760         sig.push('<');
761         sig.push_str(&generics.lifetimes.iter()
762                               .map(|l| l.lifetime.name.to_string())
763                               .collect::<Vec<_>>()
764                               .join(", "));
765         if !generics.lifetimes.is_empty() {
766             sig.push_str(", ");
767         }
768         sig.push_str(&generics.ty_params.iter()
769                               .map(|l| l.ident.to_string())
770                               .collect::<Vec<_>>()
771                               .join(", "));
772         sig.push_str("> ");
773     }
774     sig.push('(');
775     sig.push_str(&decl.inputs.iter().map(arg_to_string).collect::<Vec<_>>().join(", "));
776     sig.push(')');
777     match decl.output {
778         ast::FunctionRetTy::Default(_) => sig.push_str(" -> ()"),
779         ast::FunctionRetTy::Ty(ref t) => sig.push_str(&format!(" -> {}", ty_to_string(t))),
780     }
781
782     sig
783 }
784
785 // An AST visitor for collecting paths from patterns.
786 struct PathCollector {
787     // The Row field identifies the kind of pattern.
788     collected_paths: Vec<(NodeId, ast::Path, ast::Mutability, recorder::Row)>,
789 }
790
791 impl PathCollector {
792     fn new() -> PathCollector {
793         PathCollector { collected_paths: vec![] }
794     }
795 }
796
797 impl<'a> Visitor<'a> for PathCollector {
798     fn visit_pat(&mut self, p: &ast::Pat) {
799         match p.node {
800             PatKind::Struct(ref path, ..) => {
801                 self.collected_paths.push((p.id, path.clone(),
802                                            ast::Mutability::Mutable, recorder::TypeRef));
803             }
804             PatKind::TupleStruct(ref path, ..) |
805             PatKind::Path(_, ref path) => {
806                 self.collected_paths.push((p.id, path.clone(),
807                                            ast::Mutability::Mutable, recorder::VarRef));
808             }
809             PatKind::Ident(bm, ref path1, _) => {
810                 debug!("PathCollector, visit ident in pat {}: {:?} {:?}",
811                        path1.node,
812                        p.span,
813                        path1.span);
814                 let immut = match bm {
815                     // Even if the ref is mut, you can't change the ref, only
816                     // the data pointed at, so showing the initialising expression
817                     // is still worthwhile.
818                     ast::BindingMode::ByRef(_) => ast::Mutability::Immutable,
819                     ast::BindingMode::ByValue(mt) => mt,
820                 };
821                 // collect path for either visit_local or visit_arm
822                 let path = ast::Path::from_ident(path1.span, path1.node);
823                 self.collected_paths.push((p.id, path, immut, recorder::VarRef));
824             }
825             _ => {}
826         }
827         visit::walk_pat(self, p);
828     }
829 }
830
831 fn docs_for_attrs(attrs: &[Attribute]) -> String {
832     let mut result = String::new();
833
834     for attr in attrs {
835         if attr.check_name("doc") {
836             if let Some(val) = attr.value_str() {
837                 if attr.is_sugared_doc {
838                     result.push_str(&strip_doc_comment_decoration(&val.as_str()));
839                 } else {
840                     result.push_str(&val.as_str());
841                 }
842                 result.push('\n');
843             }
844         }
845     }
846
847     result
848 }
849
850 #[derive(Clone, Copy, Debug, RustcEncodable)]
851 pub enum Format {
852     Csv,
853     Json,
854     JsonApi,
855 }
856
857 impl Format {
858     fn extension(&self) -> &'static str {
859         match *self {
860             Format::Csv => ".csv",
861             Format::Json | Format::JsonApi => ".json",
862         }
863     }
864 }
865
866 pub fn process_crate<'l, 'tcx>(tcx: TyCtxt<'l, 'tcx, 'tcx>,
867                                krate: &ast::Crate,
868                                analysis: &'l ty::CrateAnalysis,
869                                cratename: &str,
870                                odir: Option<&Path>,
871                                format: Format) {
872     let _ignore = tcx.dep_graph.in_ignore();
873
874     assert!(analysis.glob_map.is_some());
875
876     info!("Dumping crate {}", cratename);
877
878     // find a path to dump our data to
879     let mut root_path = match env::var_os("RUST_SAVE_ANALYSIS_FOLDER") {
880         Some(val) => PathBuf::from(val),
881         None => match odir {
882             Some(val) => val.join("save-analysis"),
883             None => PathBuf::from("save-analysis-temp"),
884         },
885     };
886
887     if let Err(e) = std::fs::create_dir_all(&root_path) {
888         tcx.sess.err(&format!("Could not create directory {}: {}",
889                               root_path.display(),
890                               e));
891     }
892
893     {
894         let disp = root_path.display();
895         info!("Writing output to {}", disp);
896     }
897
898     // Create output file.
899     let executable = tcx.sess.crate_types.borrow().iter().any(|ct| *ct == CrateTypeExecutable);
900     let mut out_name = if executable {
901         "".to_owned()
902     } else {
903         "lib".to_owned()
904     };
905     out_name.push_str(&cratename);
906     out_name.push_str(&tcx.sess.opts.cg.extra_filename);
907     out_name.push_str(format.extension());
908     root_path.push(&out_name);
909     let mut output_file = File::create(&root_path).unwrap_or_else(|e| {
910         let disp = root_path.display();
911         tcx.sess.fatal(&format!("Could not open {}: {}", disp, e));
912     });
913     root_path.pop();
914     let output = &mut output_file;
915
916     let save_ctxt = SaveContext {
917         tcx: tcx,
918         tables: &ty::TypeckTables::empty(),
919         analysis: analysis,
920         span_utils: SpanUtils::new(&tcx.sess),
921     };
922
923     macro_rules! dump {
924         ($new_dumper: expr) => {{
925             let mut dumper = $new_dumper;
926             let mut visitor = DumpVisitor::new(save_ctxt, &mut dumper);
927
928             visitor.dump_crate_info(cratename, krate);
929             visit::walk_crate(&mut visitor, krate);
930         }}
931     }
932
933     match format {
934         Format::Csv => dump!(CsvDumper::new(output)),
935         Format::Json => dump!(JsonDumper::new(output)),
936         Format::JsonApi => dump!(JsonApiDumper::new(output)),
937     }
938 }
939
940 // Utility functions for the module.
941
942 // Helper function to escape quotes in a string
943 fn escape(s: String) -> String {
944     s.replace("\"", "\"\"")
945 }
946
947 // Helper function to determine if a span came from a
948 // macro expansion or syntax extension.
949 pub fn generated_code(span: Span) -> bool {
950     span.expn_id != NO_EXPANSION || span == DUMMY_SP
951 }