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