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