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