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