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