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