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