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