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