]> git.lizzy.rs Git - rust.git/blob - src/librustc_save_analysis/lib.rs
3d88b2347c17a3ed02b67e59fd62d8ed82dfd755
[rust.git] / src / librustc_save_analysis / lib.rs
1 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
2 #![feature(nll)]
3 #![deny(rust_2018_idioms)]
4 #![deny(internal)]
5 #![deny(unused_lifetimes)]
6 #![allow(unused_attributes)]
7
8 #![recursion_limit="256"]
9
10
11 mod json_dumper;
12 mod dump_visitor;
13 #[macro_use]
14 mod span_utils;
15 mod sig;
16
17 use rustc::hir;
18 use rustc::hir::def::{CtorOf, Res, DefKind as HirDefKind};
19 use rustc::hir::Node;
20 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
21 use rustc::middle::privacy::AccessLevels;
22 use rustc::middle::cstore::ExternCrate;
23 use rustc::session::config::{CrateType, Input, OutputType};
24 use rustc::ty::{self, DefIdTree, TyCtxt};
25 use rustc::{bug, span_bug};
26 use rustc_codegen_utils::link::{filename_for_metadata, out_filename};
27
28 use std::cell::Cell;
29 use std::default::Default;
30 use std::env;
31 use std::fs::File;
32 use std::path::{Path, PathBuf};
33
34 use syntax::ast::{self, Attribute, DUMMY_NODE_ID, NodeId, PatKind};
35 use syntax::source_map::Spanned;
36 use syntax::parse::lexer::comments::strip_doc_comment_decoration;
37 use syntax::print::pprust;
38 use syntax::visit::{self, Visitor};
39 use syntax::print::pprust::{arg_to_string, ty_to_string};
40 use syntax::source_map::MacroAttribute;
41 use syntax_pos::*;
42
43 use json_dumper::JsonDumper;
44 use dump_visitor::DumpVisitor;
45 use span_utils::SpanUtils;
46
47 use rls_data::{Def, DefKind, ExternalCrateData, GlobalCrateId, MacroRef, Ref, RefKind, Relation,
48                RelationKind, SpanData, Impl, ImplKind};
49 use rls_data::config::Config;
50
51 use log::{debug, error, info};
52
53
54 pub struct SaveContext<'l, 'tcx> {
55     tcx: TyCtxt<'tcx>,
56     tables: &'l ty::TypeckTables<'tcx>,
57     access_levels: &'l AccessLevels,
58     span_utils: SpanUtils<'tcx>,
59     config: Config,
60     impl_counter: Cell<u32>,
61 }
62
63 #[derive(Debug)]
64 pub enum Data {
65     RefData(Ref),
66     DefData(Def),
67     RelationData(Relation, Impl),
68 }
69
70 impl<'l, 'tcx> SaveContext<'l, 'tcx> {
71     fn span_from_span(&self, span: Span) -> SpanData {
72         use rls_span::{Column, Row};
73
74         let cm = self.tcx.sess.source_map();
75         let start = cm.lookup_char_pos(span.lo());
76         let end = cm.lookup_char_pos(span.hi());
77
78         SpanData {
79             file_name: start.file.name.to_string().into(),
80             byte_start: span.lo().0,
81             byte_end: span.hi().0,
82             line_start: Row::new_one_indexed(start.line as u32),
83             line_end: Row::new_one_indexed(end.line as u32),
84             column_start: Column::new_one_indexed(start.col.0 as u32 + 1),
85             column_end: Column::new_one_indexed(end.col.0 as u32 + 1),
86         }
87     }
88
89     // Returns path to the compilation output (e.g., libfoo-12345678.rmeta)
90     pub fn compilation_output(&self, crate_name: &str) -> PathBuf {
91         let sess = &self.tcx.sess;
92         // Save-analysis is emitted per whole session, not per each crate type
93         let crate_type = sess.crate_types.borrow()[0];
94         let outputs = &*self.tcx.output_filenames(LOCAL_CRATE);
95
96         if outputs.outputs.contains_key(&OutputType::Metadata) {
97             filename_for_metadata(sess, crate_name, outputs)
98         } else if outputs.outputs.should_codegen() {
99             out_filename(sess, crate_type, outputs, crate_name)
100         } else {
101             // Otherwise it's only a DepInfo, in which case we return early and
102             // not even reach the analysis stage.
103             unreachable!()
104         }
105     }
106
107     // List external crates used by the current crate.
108     pub fn get_external_crates(&self) -> Vec<ExternalCrateData> {
109         let mut result = Vec::with_capacity(self.tcx.crates().len());
110
111         for &n in self.tcx.crates().iter() {
112             let span = match self.tcx.extern_crate(n.as_def_id()) {
113                 Some(&ExternCrate { span, .. }) => span,
114                 None => {
115                     debug!("Skipping crate {}, no data", n);
116                     continue;
117                 }
118             };
119             let lo_loc = self.span_utils.sess.source_map().lookup_char_pos(span.lo());
120             result.push(ExternalCrateData {
121                 // FIXME: change file_name field to PathBuf in rls-data
122                 // https://github.com/nrc/rls-data/issues/7
123                 file_name: self.span_utils.make_filename_string(&lo_loc.file),
124                 num: n.as_u32(),
125                 id: GlobalCrateId {
126                     name: self.tcx.crate_name(n).to_string(),
127                     disambiguator: self.tcx.crate_disambiguator(n).to_fingerprint().as_value(),
128                 },
129             });
130         }
131
132         result
133     }
134
135     pub fn get_extern_item_data(&self, item: &ast::ForeignItem) -> Option<Data> {
136         let qualname = format!("::{}",
137             self.tcx.def_path_str(self.tcx.hir().local_def_id(item.id)));
138         match item.node {
139             ast::ForeignItemKind::Fn(ref decl, ref generics) => {
140                 filter!(self.span_utils, item.ident.span);
141
142                 Some(Data::DefData(Def {
143                     kind: DefKind::ForeignFunction,
144                     id: id_from_node_id(item.id, self),
145                     span: self.span_from_span(item.ident.span),
146                     name: item.ident.to_string(),
147                     qualname,
148                     value: make_signature(decl, generics),
149                     parent: None,
150                     children: vec![],
151                     decl_id: None,
152                     docs: self.docs_for_attrs(&item.attrs),
153                     sig: sig::foreign_item_signature(item, self),
154                     attributes: lower_attributes(item.attrs.clone(), self),
155                 }))
156             }
157             ast::ForeignItemKind::Static(ref ty, _) => {
158                 filter!(self.span_utils, item.ident.span);
159
160                 let id = id_from_node_id(item.id, self);
161                 let span = self.span_from_span(item.ident.span);
162
163                 Some(Data::DefData(Def {
164                     kind: DefKind::ForeignStatic,
165                     id,
166                     span,
167                     name: item.ident.to_string(),
168                     qualname,
169                     value: ty_to_string(ty),
170                     parent: None,
171                     children: vec![],
172                     decl_id: None,
173                     docs: self.docs_for_attrs(&item.attrs),
174                     sig: sig::foreign_item_signature(item, self),
175                     attributes: lower_attributes(item.attrs.clone(), self),
176                 }))
177             }
178             // FIXME(plietar): needs a new DefKind in rls-data
179             ast::ForeignItemKind::Ty => None,
180             ast::ForeignItemKind::Macro(..) => None,
181         }
182     }
183
184     pub fn get_item_data(&self, item: &ast::Item) -> Option<Data> {
185         match item.node {
186             ast::ItemKind::Fn(ref decl, .., ref generics, _) => {
187                 let qualname = format!("::{}",
188                     self.tcx.def_path_str(self.tcx.hir().local_def_id(item.id)));
189                 filter!(self.span_utils, item.ident.span);
190                 Some(Data::DefData(Def {
191                     kind: DefKind::Function,
192                     id: id_from_node_id(item.id, self),
193                     span: self.span_from_span(item.ident.span),
194                     name: item.ident.to_string(),
195                     qualname,
196                     value: make_signature(decl, generics),
197                     parent: None,
198                     children: vec![],
199                     decl_id: None,
200                     docs: self.docs_for_attrs(&item.attrs),
201                     sig: sig::item_signature(item, self),
202                     attributes: lower_attributes(item.attrs.clone(), self),
203                 }))
204             }
205             ast::ItemKind::Static(ref typ, ..) => {
206                 let qualname = format!("::{}",
207                     self.tcx.def_path_str(self.tcx.hir().local_def_id(item.id)));
208
209                 filter!(self.span_utils, item.ident.span);
210
211                 let id = id_from_node_id(item.id, self);
212                 let span = self.span_from_span(item.ident.span);
213
214                 Some(Data::DefData(Def {
215                     kind: DefKind::Static,
216                     id,
217                     span,
218                     name: item.ident.to_string(),
219                     qualname,
220                     value: ty_to_string(&typ),
221                     parent: None,
222                     children: vec![],
223                     decl_id: None,
224                     docs: self.docs_for_attrs(&item.attrs),
225                     sig: sig::item_signature(item, self),
226                     attributes: lower_attributes(item.attrs.clone(), self),
227                 }))
228             }
229             ast::ItemKind::Const(ref typ, _) => {
230                 let qualname = format!("::{}",
231                     self.tcx.def_path_str(self.tcx.hir().local_def_id(item.id)));
232                 filter!(self.span_utils, item.ident.span);
233
234                 let id = id_from_node_id(item.id, self);
235                 let span = self.span_from_span(item.ident.span);
236
237                 Some(Data::DefData(Def {
238                     kind: DefKind::Const,
239                     id,
240                     span,
241                     name: item.ident.to_string(),
242                     qualname,
243                     value: ty_to_string(typ),
244                     parent: None,
245                     children: vec![],
246                     decl_id: None,
247                     docs: self.docs_for_attrs(&item.attrs),
248                     sig: sig::item_signature(item, self),
249                     attributes: lower_attributes(item.attrs.clone(), self),
250                 }))
251             }
252             ast::ItemKind::Mod(ref m) => {
253                 let qualname = format!("::{}",
254                     self.tcx.def_path_str(self.tcx.hir().local_def_id(item.id)));
255
256                 let cm = self.tcx.sess.source_map();
257                 let filename = cm.span_to_filename(m.inner);
258
259                 filter!(self.span_utils, item.ident.span);
260
261                 Some(Data::DefData(Def {
262                     kind: DefKind::Mod,
263                     id: id_from_node_id(item.id, self),
264                     name: item.ident.to_string(),
265                     qualname,
266                     span: self.span_from_span(item.ident.span),
267                     value: filename.to_string(),
268                     parent: None,
269                     children: m.items
270                         .iter()
271                         .map(|i| id_from_node_id(i.id, self))
272                         .collect(),
273                     decl_id: None,
274                     docs: self.docs_for_attrs(&item.attrs),
275                     sig: sig::item_signature(item, self),
276                     attributes: lower_attributes(item.attrs.clone(), self),
277                 }))
278             }
279             ast::ItemKind::Enum(ref def, _) => {
280                 let name = item.ident.to_string();
281                 let qualname = format!("::{}",
282                     self.tcx.def_path_str(self.tcx.hir().local_def_id(item.id)));
283                 filter!(self.span_utils, item.ident.span);
284                 let variants_str = def.variants
285                     .iter()
286                     .map(|v| v.node.ident.to_string())
287                     .collect::<Vec<_>>()
288                     .join(", ");
289                 let value = format!("{}::{{{}}}", name, variants_str);
290                 Some(Data::DefData(Def {
291                     kind: DefKind::Enum,
292                     id: id_from_node_id(item.id, self),
293                     span: self.span_from_span(item.ident.span),
294                     name,
295                     qualname,
296                     value,
297                     parent: None,
298                     children: def.variants
299                         .iter()
300                         .map(|v| id_from_node_id(v.node.id, self))
301                         .collect(),
302                     decl_id: None,
303                     docs: self.docs_for_attrs(&item.attrs),
304                     sig: sig::item_signature(item, self),
305                     attributes: lower_attributes(item.attrs.clone(), self),
306                 }))
307             }
308             ast::ItemKind::Impl(.., ref trait_ref, ref typ, ref impls) => {
309                 if let ast::TyKind::Path(None, ref path) = typ.node {
310                     // Common case impl for a struct or something basic.
311                     if generated_code(path.span) {
312                         return None;
313                     }
314                     let sub_span = path.segments.last().unwrap().ident.span;
315                     filter!(self.span_utils, sub_span);
316
317                     let impl_id = self.next_impl_id();
318                     let span = self.span_from_span(sub_span);
319
320                     let type_data = self.lookup_ref_id(typ.id);
321                     type_data.map(|type_data| {
322                         Data::RelationData(Relation {
323                             kind: RelationKind::Impl {
324                                 id: impl_id,
325                             },
326                             span: span.clone(),
327                             from: id_from_def_id(type_data),
328                             to: trait_ref
329                                 .as_ref()
330                                 .and_then(|t| self.lookup_ref_id(t.ref_id))
331                                 .map(id_from_def_id)
332                                 .unwrap_or_else(|| null_id()),
333                         },
334                         Impl {
335                             id: impl_id,
336                             kind: match *trait_ref {
337                                 Some(_) => ImplKind::Direct,
338                                 None => ImplKind::Inherent,
339                             },
340                             span: span,
341                             value: String::new(),
342                             parent: None,
343                             children: impls
344                                 .iter()
345                                 .map(|i| id_from_node_id(i.id, self))
346                                 .collect(),
347                             docs: String::new(),
348                             sig: None,
349                             attributes: vec![],
350                         })
351                     })
352                 } else {
353                     None
354                 }
355             }
356             _ => {
357                 // FIXME
358                 bug!();
359             }
360         }
361     }
362
363     pub fn get_field_data(&self, field: &ast::StructField, scope: NodeId) -> Option<Def> {
364         if let Some(ident) = field.ident {
365             let name = ident.to_string();
366             let qualname = format!("::{}::{}",
367                 self.tcx.def_path_str(self.tcx.hir().local_def_id(scope)),
368                 ident);
369             filter!(self.span_utils, ident.span);
370             let def_id = self.tcx.hir().local_def_id(field.id);
371             let typ = self.tcx.type_of(def_id).to_string();
372
373
374             let id = id_from_node_id(field.id, self);
375             let span = self.span_from_span(ident.span);
376
377             Some(Def {
378                 kind: DefKind::Field,
379                 id,
380                 span,
381                 name,
382                 qualname,
383                 value: typ,
384                 parent: Some(id_from_node_id(scope, self)),
385                 children: vec![],
386                 decl_id: None,
387                 docs: self.docs_for_attrs(&field.attrs),
388                 sig: sig::field_signature(field, self),
389                 attributes: lower_attributes(field.attrs.clone(), self),
390             })
391         } else {
392             None
393         }
394     }
395
396     // FIXME would be nice to take a MethodItem here, but the ast provides both
397     // trait and impl flavours, so the caller must do the disassembly.
398     pub fn get_method_data(&self, id: ast::NodeId, ident: ast::Ident, span: Span) -> Option<Def> {
399         // The qualname for a method is the trait name or name of the struct in an impl in
400         // which the method is declared in, followed by the method's name.
401         let (qualname, parent_scope, decl_id, docs, attributes) =
402             match self.tcx.impl_of_method(self.tcx.hir().local_def_id(id)) {
403                 Some(impl_id) => match self.tcx.hir().get_if_local(impl_id) {
404                     Some(Node::Item(item)) => match item.node {
405                         hir::ItemKind::Impl(.., ref ty, _) => {
406                             let mut qualname = String::from("<");
407                             qualname.push_str(&self.tcx.hir().hir_to_pretty_string(ty.hir_id));
408
409                             let trait_id = self.tcx.trait_id_of_impl(impl_id);
410                             let mut decl_id = None;
411                             let mut docs = String::new();
412                             let mut attrs = vec![];
413                             let hir_id = self.tcx.hir().node_to_hir_id(id);
414                             if let Some(Node::ImplItem(item)) =
415                                 self.tcx.hir().find_by_hir_id(hir_id)
416                             {
417                                 docs = self.docs_for_attrs(&item.attrs);
418                                 attrs = item.attrs.to_vec();
419                             }
420
421                             if let Some(def_id) = trait_id {
422                                 // A method in a trait impl.
423                                 qualname.push_str(" as ");
424                                 qualname.push_str(&self.tcx.def_path_str(def_id));
425                                 self.tcx
426                                     .associated_items(def_id)
427                                     .find(|item| item.ident.name == ident.name)
428                                     .map(|item| decl_id = Some(item.def_id));
429                             }
430                             qualname.push_str(">");
431
432                             (qualname, trait_id, decl_id, docs, attrs)
433                         }
434                         _ => {
435                             span_bug!(
436                                 span,
437                                 "Container {:?} for method {} not an impl?",
438                                 impl_id,
439                                 id
440                             );
441                         }
442                     },
443                     r => {
444                         span_bug!(
445                             span,
446                             "Container {:?} for method {} is not a node item {:?}",
447                             impl_id,
448                             id,
449                             r
450                         );
451                     }
452                 },
453                 None => match self.tcx.trait_of_item(self.tcx.hir().local_def_id(id)) {
454                     Some(def_id) => {
455                         let mut docs = String::new();
456                         let mut attrs = vec![];
457                         let hir_id = self.tcx.hir().node_to_hir_id(id);
458
459                         if let Some(Node::TraitItem(item)) = self.tcx.hir().find_by_hir_id(hir_id) {
460                             docs = self.docs_for_attrs(&item.attrs);
461                             attrs = item.attrs.to_vec();
462                         }
463
464                         (
465                             format!("::{}", self.tcx.def_path_str(def_id)),
466                             Some(def_id),
467                             None,
468                             docs,
469                             attrs,
470                         )
471                     }
472                     None => {
473                         debug!("Could not find container for method {} at {:?}", id, span);
474                         // This is not necessarily a bug, if there was a compilation error,
475                         // the tables we need might not exist.
476                         return None;
477                     }
478                 },
479             };
480
481         let qualname = format!("{}::{}", qualname, ident.name);
482
483         filter!(self.span_utils, ident.span);
484
485         Some(Def {
486             kind: DefKind::Method,
487             id: id_from_node_id(id, self),
488             span: self.span_from_span(ident.span),
489             name: ident.name.to_string(),
490             qualname,
491             // FIXME you get better data here by using the visitor.
492             value: String::new(),
493             parent: parent_scope.map(|id| id_from_def_id(id)),
494             children: vec![],
495             decl_id: decl_id.map(|id| id_from_def_id(id)),
496             docs,
497             sig: None,
498             attributes: lower_attributes(attributes, self),
499         })
500     }
501
502     pub fn get_trait_ref_data(&self, trait_ref: &ast::TraitRef) -> Option<Ref> {
503         self.lookup_ref_id(trait_ref.ref_id).and_then(|def_id| {
504             let span = trait_ref.path.span;
505             if generated_code(span) {
506                 return None;
507             }
508             let sub_span = trait_ref.path.segments.last().unwrap().ident.span;
509             filter!(self.span_utils, sub_span);
510             let span = self.span_from_span(sub_span);
511             Some(Ref {
512                 kind: RefKind::Type,
513                 span,
514                 ref_id: id_from_def_id(def_id),
515             })
516         })
517     }
518
519     pub fn get_expr_data(&self, expr: &ast::Expr) -> Option<Data> {
520         let expr_hir_id = self.tcx.hir().node_to_hir_id(expr.id);
521         let hir_node = self.tcx.hir().expect_expr(expr_hir_id);
522         let ty = self.tables.expr_ty_adjusted_opt(&hir_node);
523         if ty.is_none() || ty.unwrap().sty == ty::Error {
524             return None;
525         }
526         match expr.node {
527             ast::ExprKind::Field(ref sub_ex, ident) => {
528                 let sub_ex_hir_id = self.tcx.hir().node_to_hir_id(sub_ex.id);
529                 let hir_node = match self.tcx.hir().find_by_hir_id(sub_ex_hir_id) {
530                     Some(Node::Expr(expr)) => expr,
531                     _ => {
532                         debug!(
533                             "Missing or weird node for sub-expression {} in {:?}",
534                             sub_ex.id,
535                             expr
536                         );
537                         return None;
538                     }
539                 };
540                 match self.tables.expr_ty_adjusted(&hir_node).sty {
541                     ty::Adt(def, _) if !def.is_enum() => {
542                         let variant = &def.non_enum_variant();
543                         let index = self.tcx.find_field_index(ident, variant).unwrap();
544                         filter!(self.span_utils, ident.span);
545                         let span = self.span_from_span(ident.span);
546                         return Some(Data::RefData(Ref {
547                             kind: RefKind::Variable,
548                             span,
549                             ref_id: id_from_def_id(variant.fields[index].did),
550                         }));
551                     }
552                     ty::Tuple(..) => None,
553                     _ => {
554                         debug!("Expected struct or union type, found {:?}", ty);
555                         None
556                     }
557                 }
558             }
559             ast::ExprKind::Struct(ref path, ..) => {
560                 match self.tables.expr_ty_adjusted(&hir_node).sty {
561                     ty::Adt(def, _) if !def.is_enum() => {
562                         let sub_span = path.segments.last().unwrap().ident.span;
563                         filter!(self.span_utils, sub_span);
564                         let span = self.span_from_span(sub_span);
565                         Some(Data::RefData(Ref {
566                             kind: RefKind::Type,
567                             span,
568                             ref_id: id_from_def_id(def.did),
569                         }))
570                     }
571                     _ => {
572                         // FIXME ty could legitimately be an enum, but then we will fail
573                         // later if we try to look up the fields.
574                         debug!("expected struct or union, found {:?}", ty);
575                         None
576                     }
577                 }
578             }
579             ast::ExprKind::MethodCall(ref seg, ..) => {
580                 let expr_hir_id = self.tcx.hir().definitions().node_to_hir_id(expr.id);
581                 let method_id = match self.tables.type_dependent_def_id(expr_hir_id) {
582                     Some(id) => id,
583                     None => {
584                         debug!("Could not resolve method id for {:?}", expr);
585                         return None;
586                     }
587                 };
588                 let (def_id, decl_id) = match self.tcx.associated_item(method_id).container {
589                     ty::ImplContainer(_) => (Some(method_id), None),
590                     ty::TraitContainer(_) => (None, Some(method_id)),
591                 };
592                 let sub_span = seg.ident.span;
593                 filter!(self.span_utils, sub_span);
594                 let span = self.span_from_span(sub_span);
595                 Some(Data::RefData(Ref {
596                     kind: RefKind::Function,
597                     span,
598                     ref_id: def_id
599                         .or(decl_id)
600                         .map(|id| id_from_def_id(id))
601                         .unwrap_or_else(|| null_id()),
602                 }))
603             }
604             ast::ExprKind::Path(_, ref path) => {
605                 self.get_path_data(expr.id, path).map(|d| Data::RefData(d))
606             }
607             _ => {
608                 // FIXME
609                 bug!();
610             }
611         }
612     }
613
614     pub fn get_path_res(&self, id: NodeId) -> Res {
615         let hir_id = self.tcx.hir().node_to_hir_id(id);
616         match self.tcx.hir().get(hir_id) {
617             Node::TraitRef(tr) => tr.path.res,
618
619             Node::Item(&hir::Item {
620                 node: hir::ItemKind::Use(ref path, _),
621                 ..
622             }) |
623             Node::Visibility(&Spanned {
624                 node: hir::VisibilityKind::Restricted { ref path, .. }, .. }) => path.res,
625
626             Node::PathSegment(seg) => {
627                 match seg.res {
628                     Some(res) if res != Res::Err => res,
629                     _ => {
630                         let parent_node = self.tcx.hir().get_parent_node(hir_id);
631                         self.get_path_res(self.tcx.hir().hir_to_node_id(parent_node))
632                     },
633                 }
634             }
635
636             Node::Expr(&hir::Expr {
637                 node: hir::ExprKind::Struct(ref qpath, ..),
638                 ..
639             }) => {
640                 self.tables.qpath_res(qpath, hir_id)
641             }
642
643             Node::Expr(&hir::Expr {
644                 node: hir::ExprKind::Path(ref qpath),
645                 ..
646             }) |
647             Node::Pat(&hir::Pat {
648                 node: hir::PatKind::Path(ref qpath),
649                 ..
650             }) |
651             Node::Pat(&hir::Pat {
652                 node: hir::PatKind::Struct(ref qpath, ..),
653                 ..
654             }) |
655             Node::Pat(&hir::Pat {
656                 node: hir::PatKind::TupleStruct(ref qpath, ..),
657                 ..
658             }) |
659             Node::Ty(&hir::Ty {
660                 node: hir::TyKind::Path(ref qpath),
661                 ..
662             }) => {
663                 self.tables.qpath_res(qpath, hir_id)
664             }
665
666             Node::Binding(&hir::Pat {
667                 node: hir::PatKind::Binding(_, canonical_id, ..),
668                 ..
669             }) => Res::Local(canonical_id),
670
671             _ => Res::Err,
672         }
673     }
674
675     pub fn get_path_data(&self, id: NodeId, path: &ast::Path) -> Option<Ref> {
676         path.segments
677             .last()
678             .and_then(|seg| {
679                 self.get_path_segment_data(seg)
680                     .or_else(|| self.get_path_segment_data_with_id(seg, id))
681             })
682     }
683
684     pub fn get_path_segment_data(&self, path_seg: &ast::PathSegment) -> Option<Ref> {
685         self.get_path_segment_data_with_id(path_seg, path_seg.id)
686     }
687
688     fn get_path_segment_data_with_id(
689         &self,
690         path_seg: &ast::PathSegment,
691         id: NodeId,
692     ) -> Option<Ref> {
693         // Returns true if the path is function type sugar, e.g., `Fn(A) -> B`.
694         fn fn_type(seg: &ast::PathSegment) -> bool {
695             if let Some(ref generic_args) = seg.args {
696                 if let ast::GenericArgs::Parenthesized(_) = **generic_args {
697                     return true;
698                 }
699             }
700             false
701         }
702
703         if id == DUMMY_NODE_ID {
704             return None;
705         }
706
707         let res = self.get_path_res(id);
708         let span = path_seg.ident.span;
709         filter!(self.span_utils, span);
710         let span = self.span_from_span(span);
711
712         match res {
713             Res::Local(id) => {
714                 Some(Ref {
715                     kind: RefKind::Variable,
716                     span,
717                     ref_id: id_from_node_id(self.tcx.hir().hir_to_node_id(id), self),
718                 })
719             }
720             Res::Def(HirDefKind::Trait, def_id) if fn_type(path_seg) => {
721                 Some(Ref {
722                     kind: RefKind::Type,
723                     span,
724                     ref_id: id_from_def_id(def_id),
725                 })
726             }
727             Res::Def(HirDefKind::Struct, def_id) |
728             Res::Def(HirDefKind::Variant, def_id) |
729             Res::Def(HirDefKind::Union, def_id) |
730             Res::Def(HirDefKind::Enum, def_id) |
731             Res::Def(HirDefKind::TyAlias, def_id) |
732             Res::Def(HirDefKind::ForeignTy, def_id) |
733             Res::Def(HirDefKind::TraitAlias, def_id) |
734             Res::Def(HirDefKind::AssocExistential, def_id) |
735             Res::Def(HirDefKind::AssocTy, def_id) |
736             Res::Def(HirDefKind::Trait, def_id) |
737             Res::Def(HirDefKind::Existential, def_id) |
738             Res::Def(HirDefKind::TyParam, def_id) => {
739                 Some(Ref {
740                     kind: RefKind::Type,
741                     span,
742                     ref_id: id_from_def_id(def_id),
743                 })
744             }
745             Res::Def(HirDefKind::ConstParam, def_id) => {
746                 Some(Ref {
747                     kind: RefKind::Variable,
748                     span,
749                     ref_id: id_from_def_id(def_id),
750                 })
751             }
752             Res::Def(HirDefKind::Ctor(CtorOf::Struct, ..), def_id) => {
753                 // This is a reference to a tuple struct where the def_id points
754                 // to an invisible constructor function. That is not a very useful
755                 // def, so adjust to point to the tuple struct itself.
756                 let parent_def_id = self.tcx.parent(def_id).unwrap();
757                 Some(Ref {
758                     kind: RefKind::Type,
759                     span,
760                     ref_id: id_from_def_id(parent_def_id),
761                 })
762             }
763             Res::Def(HirDefKind::Static, _) |
764             Res::Def(HirDefKind::Const, _) |
765             Res::Def(HirDefKind::AssocConst, _) |
766             Res::Def(HirDefKind::Ctor(..), _) => {
767                 Some(Ref {
768                     kind: RefKind::Variable,
769                     span,
770                     ref_id: id_from_def_id(res.def_id()),
771                 })
772             }
773             Res::Def(HirDefKind::Method, decl_id) => {
774                 let def_id = if decl_id.is_local() {
775                     let ti = self.tcx.associated_item(decl_id);
776                     self.tcx
777                         .associated_items(ti.container.id())
778                         .find(|item| item.ident.name == ti.ident.name &&
779                                      item.defaultness.has_value())
780                         .map(|item| item.def_id)
781                 } else {
782                     None
783                 };
784                 Some(Ref {
785                     kind: RefKind::Function,
786                     span,
787                     ref_id: id_from_def_id(def_id.unwrap_or(decl_id)),
788                 })
789             }
790             Res::Def(HirDefKind::Fn, def_id) => {
791                 Some(Ref {
792                     kind: RefKind::Function,
793                     span,
794                     ref_id: id_from_def_id(def_id),
795                 })
796             }
797             Res::Def(HirDefKind::Mod, def_id) => {
798                 Some(Ref {
799                     kind: RefKind::Mod,
800                     span,
801                     ref_id: id_from_def_id(def_id),
802                 })
803             }
804             Res::PrimTy(..) |
805             Res::SelfTy(..) |
806             Res::Def(HirDefKind::Macro(..), _) |
807             Res::ToolMod |
808             Res::NonMacroAttr(..) |
809             Res::SelfCtor(..) |
810             Res::Err => None,
811         }
812     }
813
814     pub fn get_field_ref_data(
815         &self,
816         field_ref: &ast::Field,
817         variant: &ty::VariantDef,
818     ) -> Option<Ref> {
819         filter!(self.span_utils, field_ref.ident.span);
820         self.tcx.find_field_index(field_ref.ident, variant).map(|index| {
821             let span = self.span_from_span(field_ref.ident.span);
822             Ref {
823                 kind: RefKind::Variable,
824                 span,
825                 ref_id: id_from_def_id(variant.fields[index].did),
826             }
827         })
828     }
829
830     /// Attempt to return MacroRef for any AST node.
831     ///
832     /// For a given piece of AST defined by the supplied Span and NodeId,
833     /// returns `None` if the node is not macro-generated or the span is malformed,
834     /// else uses the expansion callsite and callee to return some MacroRef.
835     pub fn get_macro_use_data(&self, span: Span) -> Option<MacroRef> {
836         if !generated_code(span) {
837             return None;
838         }
839         // Note we take care to use the source callsite/callee, to handle
840         // nested expansions and ensure we only generate data for source-visible
841         // macro uses.
842         let callsite = span.source_callsite();
843         let callsite_span = self.span_from_span(callsite);
844         let callee = span.source_callee()?;
845         let callee_span = callee.def_site?;
846
847         // Ignore attribute macros, their spans are usually mangled
848         if let MacroAttribute(_) = callee.format {
849             return None;
850         }
851
852         // If the callee is an imported macro from an external crate, need to get
853         // the source span and name from the session, as their spans are localized
854         // when read in, and no longer correspond to the source.
855         if let Some(mac) = self.tcx
856             .sess
857             .imported_macro_spans
858             .borrow()
859             .get(&callee_span)
860         {
861             let &(ref mac_name, mac_span) = mac;
862             let mac_span = self.span_from_span(mac_span);
863             return Some(MacroRef {
864                 span: callsite_span,
865                 qualname: mac_name.clone(), // FIXME: generate the real qualname
866                 callee_span: mac_span,
867             });
868         }
869
870         let callee_span = self.span_from_span(callee_span);
871         Some(MacroRef {
872             span: callsite_span,
873             qualname: callee.format.name().to_string(), // FIXME: generate the real qualname
874             callee_span,
875         })
876     }
877
878     fn lookup_ref_id(&self, ref_id: NodeId) -> Option<DefId> {
879         match self.get_path_res(ref_id) {
880             Res::PrimTy(_) | Res::SelfTy(..) | Res::Err => None,
881             def => Some(def.def_id()),
882         }
883     }
884
885     fn docs_for_attrs(&self, attrs: &[Attribute]) -> String {
886         let mut result = String::new();
887
888         for attr in attrs {
889             if attr.check_name(sym::doc) {
890                 if let Some(val) = attr.value_str() {
891                     if attr.is_sugared_doc {
892                         result.push_str(&strip_doc_comment_decoration(&val.as_str()));
893                     } else {
894                         result.push_str(&val.as_str());
895                     }
896                     result.push('\n');
897                 } else if let Some(meta_list) = attr.meta_item_list() {
898                     meta_list.into_iter()
899                              .filter(|it| it.check_name(sym::include))
900                              .filter_map(|it| it.meta_item_list().map(|l| l.to_owned()))
901                              .flat_map(|it| it)
902                              .filter(|meta| meta.check_name(sym::contents))
903                              .filter_map(|meta| meta.value_str())
904                              .for_each(|val| {
905                                  result.push_str(&val.as_str());
906                                  result.push('\n');
907                              });
908                 }
909             }
910         }
911
912         if !self.config.full_docs {
913             if let Some(index) = result.find("\n\n") {
914                 result.truncate(index);
915             }
916         }
917
918         result
919     }
920
921     fn next_impl_id(&self) -> u32 {
922         let next = self.impl_counter.get();
923         self.impl_counter.set(next + 1);
924         next
925     }
926 }
927
928 fn make_signature(decl: &ast::FnDecl, generics: &ast::Generics) -> String {
929     let mut sig = "fn ".to_owned();
930     if !generics.params.is_empty() {
931         sig.push('<');
932         sig.push_str(&generics
933             .params
934             .iter()
935             .map(|param| param.ident.to_string())
936             .collect::<Vec<_>>()
937             .join(", "));
938         sig.push_str("> ");
939     }
940     sig.push('(');
941     sig.push_str(&decl.inputs
942         .iter()
943         .map(arg_to_string)
944         .collect::<Vec<_>>()
945         .join(", "));
946     sig.push(')');
947     match decl.output {
948         ast::FunctionRetTy::Default(_) => sig.push_str(" -> ()"),
949         ast::FunctionRetTy::Ty(ref t) => sig.push_str(&format!(" -> {}", ty_to_string(t))),
950     }
951
952     sig
953 }
954
955 // An AST visitor for collecting paths (e.g., the names of structs) and formal
956 // variables (idents) from patterns.
957 struct PathCollector<'l> {
958     collected_paths: Vec<(NodeId, &'l ast::Path)>,
959     collected_idents: Vec<(NodeId, ast::Ident, ast::Mutability)>,
960 }
961
962 impl<'l> PathCollector<'l> {
963     fn new() -> PathCollector<'l> {
964         PathCollector {
965             collected_paths: vec![],
966             collected_idents: vec![],
967         }
968     }
969 }
970
971 impl<'l> Visitor<'l> for PathCollector<'l> {
972     fn visit_pat(&mut self, p: &'l ast::Pat) {
973         match p.node {
974             PatKind::Struct(ref path, ..) => {
975                 self.collected_paths.push((p.id, path));
976             }
977             PatKind::TupleStruct(ref path, ..) | PatKind::Path(_, ref path) => {
978                 self.collected_paths.push((p.id, path));
979             }
980             PatKind::Ident(bm, ident, _) => {
981                 debug!(
982                     "PathCollector, visit ident in pat {}: {:?} {:?}",
983                     ident,
984                     p.span,
985                     ident.span
986                 );
987                 let immut = match bm {
988                     // Even if the ref is mut, you can't change the ref, only
989                     // the data pointed at, so showing the initialising expression
990                     // is still worthwhile.
991                     ast::BindingMode::ByRef(_) => ast::Mutability::Immutable,
992                     ast::BindingMode::ByValue(mt) => mt,
993                 };
994                 self.collected_idents
995                     .push((p.id, ident, immut));
996             }
997             _ => {}
998         }
999         visit::walk_pat(self, p);
1000     }
1001 }
1002
1003 /// Defines what to do with the results of saving the analysis.
1004 pub trait SaveHandler {
1005     fn save<'l, 'tcx>(
1006         &mut self,
1007         save_ctxt: SaveContext<'l, 'tcx>,
1008         krate: &ast::Crate,
1009         cratename: &str,
1010         input: &'l Input,
1011     );
1012 }
1013
1014 /// Dump the save-analysis results to a file.
1015 pub struct DumpHandler<'a> {
1016     odir: Option<&'a Path>,
1017     cratename: String,
1018 }
1019
1020 impl<'a> DumpHandler<'a> {
1021     pub fn new(odir: Option<&'a Path>, cratename: &str) -> DumpHandler<'a> {
1022         DumpHandler {
1023             odir,
1024             cratename: cratename.to_owned(),
1025         }
1026     }
1027
1028     fn output_file(&self, ctx: &SaveContext<'_, '_>) -> (File, PathBuf) {
1029         let sess = &ctx.tcx.sess;
1030         let file_name = match ctx.config.output_file {
1031             Some(ref s) => PathBuf::from(s),
1032             None => {
1033                 let mut root_path = match self.odir {
1034                     Some(val) => val.join("save-analysis"),
1035                     None => PathBuf::from("save-analysis-temp"),
1036                 };
1037
1038                 if let Err(e) = std::fs::create_dir_all(&root_path) {
1039                     error!("Could not create directory {}: {}", root_path.display(), e);
1040                 }
1041
1042                 let executable = sess.crate_types
1043                     .borrow()
1044                     .iter()
1045                     .any(|ct| *ct == CrateType::Executable);
1046                 let mut out_name = if executable {
1047                     String::new()
1048                 } else {
1049                     "lib".to_owned()
1050                 };
1051                 out_name.push_str(&self.cratename);
1052                 out_name.push_str(&sess.opts.cg.extra_filename);
1053                 out_name.push_str(".json");
1054                 root_path.push(&out_name);
1055
1056                 root_path
1057             }
1058         };
1059
1060         info!("Writing output to {}", file_name.display());
1061
1062         let output_file = File::create(&file_name).unwrap_or_else(
1063             |e| sess.fatal(&format!("Could not open {}: {}", file_name.display(), e)),
1064         );
1065
1066         (output_file, file_name)
1067     }
1068 }
1069
1070 impl<'a> SaveHandler for DumpHandler<'a> {
1071     fn save<'l, 'tcx>(
1072         &mut self,
1073         save_ctxt: SaveContext<'l, 'tcx>,
1074         krate: &ast::Crate,
1075         cratename: &str,
1076         input: &'l Input,
1077     ) {
1078         let sess = &save_ctxt.tcx.sess;
1079         let file_name = {
1080             let (mut output, file_name) = self.output_file(&save_ctxt);
1081             let mut dumper = JsonDumper::new(&mut output, save_ctxt.config.clone());
1082             let mut visitor = DumpVisitor::new(save_ctxt, &mut dumper);
1083
1084             visitor.dump_crate_info(cratename, krate);
1085             visitor.dump_compilation_options(input, cratename);
1086             visit::walk_crate(&mut visitor, krate);
1087
1088             file_name
1089         };
1090
1091         if sess.opts.debugging_opts.emit_artifact_notifications {
1092             sess.parse_sess.span_diagnostic
1093                 .emit_artifact_notification(&file_name, "save-analysis");
1094         }
1095     }
1096 }
1097
1098 /// Call a callback with the results of save-analysis.
1099 pub struct CallbackHandler<'b> {
1100     pub callback: &'b mut dyn FnMut(&rls_data::Analysis),
1101 }
1102
1103 impl<'b> SaveHandler for CallbackHandler<'b> {
1104     fn save<'l, 'tcx>(
1105         &mut self,
1106         save_ctxt: SaveContext<'l, 'tcx>,
1107         krate: &ast::Crate,
1108         cratename: &str,
1109         input: &'l Input,
1110     ) {
1111         // We're using the JsonDumper here because it has the format of the
1112         // save-analysis results that we will pass to the callback. IOW, we are
1113         // using the JsonDumper to collect the save-analysis results, but not
1114         // actually to dump them to a file. This is all a bit convoluted and
1115         // there is certainly a simpler design here trying to get out (FIXME).
1116         let mut dumper = JsonDumper::with_callback(self.callback, save_ctxt.config.clone());
1117         let mut visitor = DumpVisitor::new(save_ctxt, &mut dumper);
1118
1119         visitor.dump_crate_info(cratename, krate);
1120         visitor.dump_compilation_options(input, cratename);
1121         visit::walk_crate(&mut visitor, krate);
1122     }
1123 }
1124
1125 pub fn process_crate<'l, 'tcx, H: SaveHandler>(
1126     tcx: TyCtxt<'tcx>,
1127     krate: &ast::Crate,
1128     cratename: &str,
1129     input: &'l Input,
1130     config: Option<Config>,
1131     mut handler: H,
1132 ) {
1133     tcx.dep_graph.with_ignore(|| {
1134         info!("Dumping crate {}", cratename);
1135
1136         // Privacy checking requires and is done after type checking; use a
1137         // fallback in case the access levels couldn't have been correctly computed.
1138         let access_levels = match tcx.sess.compile_status() {
1139             Ok(..) => tcx.privacy_access_levels(LOCAL_CRATE),
1140             Err(..) => tcx.arena.alloc(AccessLevels::default()),
1141         };
1142
1143         let save_ctxt = SaveContext {
1144             tcx,
1145             tables: &ty::TypeckTables::empty(None),
1146             access_levels: &access_levels,
1147             span_utils: SpanUtils::new(&tcx.sess),
1148             config: find_config(config),
1149             impl_counter: Cell::new(0),
1150         };
1151
1152         handler.save(save_ctxt, krate, cratename, input)
1153     })
1154 }
1155
1156 fn find_config(supplied: Option<Config>) -> Config {
1157     if let Some(config) = supplied {
1158         return config;
1159     }
1160
1161     match env::var_os("RUST_SAVE_ANALYSIS_CONFIG") {
1162         None => Config::default(),
1163         Some(config) => config.to_str()
1164             .ok_or(())
1165             .map_err(|_| error!("`RUST_SAVE_ANALYSIS_CONFIG` isn't UTF-8"))
1166             .and_then(|cfg|  serde_json::from_str(cfg)
1167                 .map_err(|_| error!("Could not deserialize save-analysis config"))
1168             ).unwrap_or_default()
1169     }
1170 }
1171
1172 // Utility functions for the module.
1173
1174 // Helper function to escape quotes in a string
1175 fn escape(s: String) -> String {
1176     s.replace("\"", "\"\"")
1177 }
1178
1179 // Helper function to determine if a span came from a
1180 // macro expansion or syntax extension.
1181 fn generated_code(span: Span) -> bool {
1182     span.ctxt() != NO_EXPANSION || span.is_dummy()
1183 }
1184
1185 // DefId::index is a newtype and so the JSON serialisation is ugly. Therefore
1186 // we use our own Id which is the same, but without the newtype.
1187 fn id_from_def_id(id: DefId) -> rls_data::Id {
1188     rls_data::Id {
1189         krate: id.krate.as_u32(),
1190         index: id.index.as_u32(),
1191     }
1192 }
1193
1194 fn id_from_node_id(id: NodeId, scx: &SaveContext<'_, '_>) -> rls_data::Id {
1195     let def_id = scx.tcx.hir().opt_local_def_id(id);
1196     def_id.map(|id| id_from_def_id(id)).unwrap_or_else(|| {
1197         // Create a *fake* `DefId` out of a `NodeId` by subtracting the `NodeId`
1198         // out of the maximum u32 value. This will work unless you have *billions*
1199         // of definitions in a single crate (very unlikely to actually happen).
1200         rls_data::Id {
1201             krate: LOCAL_CRATE.as_u32(),
1202             index: !id.as_u32(),
1203         }
1204     })
1205 }
1206
1207 fn null_id() -> rls_data::Id {
1208     rls_data::Id {
1209         krate: u32::max_value(),
1210         index: u32::max_value(),
1211     }
1212 }
1213
1214 fn lower_attributes(attrs: Vec<Attribute>, scx: &SaveContext<'_, '_>) -> Vec<rls_data::Attribute> {
1215     attrs.into_iter()
1216     // Only retain real attributes. Doc comments are lowered separately.
1217     .filter(|attr| attr.path != sym::doc)
1218     .map(|mut attr| {
1219         // Remove the surrounding '#[..]' or '#![..]' of the pretty printed
1220         // attribute. First normalize all inner attribute (#![..]) to outer
1221         // ones (#[..]), then remove the two leading and the one trailing character.
1222         attr.style = ast::AttrStyle::Outer;
1223         let value = pprust::attribute_to_string(&attr);
1224         // This str slicing works correctly, because the leading and trailing characters
1225         // are in the ASCII range and thus exactly one byte each.
1226         let value = value[2..value.len()-1].to_string();
1227
1228         rls_data::Attribute {
1229             value,
1230             span: scx.span_from_span(attr.span),
1231         }
1232     }).collect()
1233 }