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