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