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