]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_save_analysis/src/lib.rs
New upstream version 1.64.0+dfsg1
[rustc.git] / compiler / rustc_save_analysis / src / lib.rs
CommitLineData
1b1a35ee 1#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
94222f64 2#![feature(if_let_guard)]
5099ac24 3#![feature(let_else)]
dfeec247 4#![recursion_limit = "256"]
5e7ed085 5#![allow(rustc::potential_query_instability)]
7cac9316 6
a7813a04 7mod dump_visitor;
dfeec247 8mod dumper;
a7813a04 9#[macro_use]
041b39d2
XL
10mod span_utils;
11mod sig;
a7813a04 12
3dfed10e
XL
13use rustc_ast as ast;
14use rustc_ast::util::comments::beautify_doc_string;
f035d41b 15use rustc_ast_pretty::pprust::attribute_to_string;
dfeec247 16use rustc_hir as hir;
f035d41b 17use rustc_hir::def::{DefKind as HirDefKind, Res};
dfeec247 18use rustc_hir::def_id::{DefId, LOCAL_CRATE};
f035d41b 19use rustc_hir::intravisit::{self, Visitor};
dfeec247 20use rustc_hir::Node;
f035d41b 21use rustc_hir_pretty::{enum_def_to_string, fn_to_string, ty_to_string};
5099ac24 22use rustc_middle::hir::nested_filter;
ba9703b0 23use rustc_middle::middle::privacy::AccessLevels;
1b1a35ee 24use rustc_middle::ty::{self, print::with_no_trimmed_paths, DefIdTree, TyCtxt};
ba9703b0
XL
25use rustc_middle::{bug, span_bug};
26use rustc_session::config::{CrateType, Input, OutputType};
c295e0f8 27use rustc_session::cstore::ExternCrate;
ba9703b0 28use rustc_session::output::{filename_for_metadata, out_filename};
f9f354fc 29use rustc_span::symbol::Ident;
74b04a01 30use rustc_span::*;
1a4d82fc 31
2c00a5a8 32use std::cell::Cell;
3b2f2976 33use std::default::Default;
85aaf69f 34use std::env;
476ff2be 35use std::fs::File;
dc9dc135 36use std::io::BufWriter;
c34b1796 37use std::path::{Path, PathBuf};
1a4d82fc 38
041b39d2
XL
39use dump_visitor::DumpVisitor;
40use span_utils::SpanUtils;
41
3b2f2976 42use rls_data::config::Config;
dfeec247
XL
43use rls_data::{
44 Analysis, Def, DefKind, ExternalCrateData, GlobalCrateId, Impl, ImplKind, MacroRef, Ref,
45 RefKind, Relation, RelationKind, SpanData,
46};
041b39d2 47
3dfed10e 48use tracing::{debug, error, info};
9fa01778 49
f035d41b 50pub struct SaveContext<'tcx> {
dc9dc135 51 tcx: TyCtxt<'tcx>,
3dfed10e 52 maybe_typeck_results: Option<&'tcx ty::TypeckResults<'tcx>>,
f035d41b 53 access_levels: &'tcx AccessLevels,
a7813a04 54 span_utils: SpanUtils<'tcx>,
3b2f2976 55 config: Config,
2c00a5a8 56 impl_counter: Cell<u32>,
7453a54e
SL
57}
58
041b39d2
XL
59#[derive(Debug)]
60pub enum Data {
041b39d2
XL
61 RefData(Ref),
62 DefData(Def),
2c00a5a8 63 RelationData(Relation, Impl),
041b39d2
XL
64}
65
f035d41b 66impl<'tcx> SaveContext<'tcx> {
3dfed10e 67 /// Gets the type-checking results for the current body.
f035d41b
XL
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]
3dfed10e
XL
71 fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> {
72 self.maybe_typeck_results.expect("`SaveContext::typeck_results` called outside of body")
f035d41b
XL
73 }
74
041b39d2 75 fn span_from_span(&self, span: Span) -> SpanData {
abe05a73 76 use rls_span::{Column, Row};
041b39d2 77
74b04a01
XL
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());
041b39d2
XL
81
82 SpanData {
17df50a5 83 file_name: start.file.name.prefer_remapped().to_string().into(),
ea8adc8c
XL
84 byte_start: span.lo().0,
85 byte_end: span.hi().0,
041b39d2
XL
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
0731742a 93 // Returns path to the compilation output (e.g., libfoo-12345678.rmeta)
0bf4aa26
XL
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
f9f354fc 97 let crate_type = sess.crate_types()[0];
17df50a5 98 let outputs = &*self.tcx.output_filenames(());
0bf4aa26
XL
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
d9579d0f 111 // List external crates used by the current crate.
041b39d2 112 pub fn get_external_crates(&self) -> Vec<ExternalCrateData> {
136023e0 113 let mut result = Vec::with_capacity(self.tcx.crates(()).len());
1a4d82fc 114
136023e0 115 for &n in self.tcx.crates(()).iter() {
5e7ed085
FG
116 let Some(&ExternCrate { span, .. }) = self.tcx.extern_crate(n.as_def_id()) else {
117 debug!("skipping crate {}, no data", n);
118 continue;
a7813a04 119 };
b7449926 120 let lo_loc = self.span_utils.sess.source_map().lookup_char_pos(span.lo());
041b39d2 121 result.push(ExternalCrateData {
ff7c6d11
XL
122 // FIXME: change file_name field to PathBuf in rls-data
123 // https://github.com/nrc/rls-data/issues/7
0bf4aa26 124 file_name: self.span_utils.make_filename_string(&lo_loc.file),
abe05a73
XL
125 num: n.as_u32(),
126 id: GlobalCrateId {
127 name: self.tcx.crate_name(n).to_string(),
136023e0
XL
128 disambiguator: (
129 self.tcx.def_path_hash(n.as_def_id()).stable_crate_id().to_u64(),
130 0,
131 ),
abe05a73 132 },
b039eaaf 133 });
92a42be0 134 }
1a4d82fc
JJ
135
136 result
137 }
138
f035d41b 139 pub fn get_extern_item_data(&self, item: &hir::ForeignItem<'_>) -> Option<Data> {
6a06907d 140 let def_id = item.def_id.to_def_id();
f035d41b 141 let qualname = format!("::{}", self.tcx.def_path_str(def_id));
6a06907d 142 let attrs = self.tcx.hir().attrs(item.hir_id());
e74abb32 143 match item.kind {
f035d41b 144 hir::ForeignItemKind::Fn(ref decl, arg_names, ref generics) => {
13cf67c4 145 filter!(self.span_utils, item.ident.span);
041b39d2
XL
146
147 Some(Data::DefData(Def {
b7449926 148 kind: DefKind::ForeignFunction,
f035d41b 149 id: id_from_def_id(def_id),
13cf67c4 150 span: self.span_from_span(item.ident.span),
cc61c64b 151 name: item.ident.to_string(),
041b39d2 152 qualname,
f035d41b
XL
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,
6a06907d 160 abi: self.tcx.hir().get_foreign_abi(item.hir_id()),
f035d41b
XL
161 // functions in extern block cannot be async
162 asyncness: hir::IsAsync::NotAsync,
163 },
164 Some(item.ident.name),
165 generics,
f035d41b
XL
166 arg_names,
167 None,
168 ),
cc61c64b 169 parent: None,
041b39d2
XL
170 children: vec![],
171 decl_id: None,
6a06907d 172 docs: self.docs_for_attrs(attrs),
041b39d2 173 sig: sig::foreign_item_signature(item, self),
6a06907d 174 attributes: lower_attributes(attrs.to_vec(), self),
cc61c64b
XL
175 }))
176 }
f035d41b 177 hir::ForeignItemKind::Static(ref ty, _) => {
13cf67c4 178 filter!(self.span_utils, item.ident.span);
041b39d2 179
f035d41b 180 let id = id_from_def_id(def_id);
13cf67c4 181 let span = self.span_from_span(item.ident.span);
041b39d2
XL
182
183 Some(Data::DefData(Def {
b7449926 184 kind: DefKind::ForeignStatic,
041b39d2
XL
185 id,
186 span,
cc61c64b 187 name: item.ident.to_string(),
041b39d2
XL
188 qualname,
189 value: ty_to_string(ty),
cc61c64b 190 parent: None,
041b39d2
XL
191 children: vec![],
192 decl_id: None,
6a06907d 193 docs: self.docs_for_attrs(attrs),
041b39d2 194 sig: sig::foreign_item_signature(item, self),
6a06907d 195 attributes: lower_attributes(attrs.to_vec(), self),
cc61c64b
XL
196 }))
197 }
abe05a73 198 // FIXME(plietar): needs a new DefKind in rls-data
f035d41b 199 hir::ForeignItemKind::Type => None,
cc61c64b
XL
200 }
201 }
202
f035d41b 203 pub fn get_item_data(&self, item: &hir::Item<'_>) -> Option<Data> {
6a06907d
XL
204 let def_id = item.def_id.to_def_id();
205 let attrs = self.tcx.hir().attrs(item.hir_id());
e74abb32 206 match item.kind {
f035d41b
XL
207 hir::ItemKind::Fn(ref sig, ref generics, _) => {
208 let qualname = format!("::{}", self.tcx.def_path_str(def_id));
13cf67c4 209 filter!(self.span_utils, item.ident.span);
041b39d2
XL
210 Some(Data::DefData(Def {
211 kind: DefKind::Function,
f035d41b 212 id: id_from_def_id(def_id),
13cf67c4 213 span: self.span_from_span(item.ident.span),
3157f602 214 name: item.ident.to_string(),
041b39d2 215 qualname,
f035d41b
XL
216 value: fn_to_string(
217 sig.decl,
218 sig.header,
219 Some(item.ident.name),
220 generics,
f035d41b
XL
221 &[],
222 None,
223 ),
9e0c209e 224 parent: None,
041b39d2
XL
225 children: vec![],
226 decl_id: None,
6a06907d 227 docs: self.docs_for_attrs(attrs),
041b39d2 228 sig: sig::item_signature(item, self),
6a06907d 229 attributes: lower_attributes(attrs.to_vec(), self),
7453a54e 230 }))
1a4d82fc 231 }
f035d41b
XL
232 hir::ItemKind::Static(ref typ, ..) => {
233 let qualname = format!("::{}", self.tcx.def_path_str(def_id));
1a4d82fc 234
13cf67c4 235 filter!(self.span_utils, item.ident.span);
041b39d2 236
f035d41b 237 let id = id_from_def_id(def_id);
13cf67c4 238 let span = self.span_from_span(item.ident.span);
041b39d2
XL
239
240 Some(Data::DefData(Def {
241 kind: DefKind::Static,
242 id,
243 span,
c1a9b12d 244 name: item.ident.to_string(),
041b39d2
XL
245 qualname,
246 value: ty_to_string(&typ),
9e0c209e 247 parent: None,
041b39d2
XL
248 children: vec![],
249 decl_id: None,
6a06907d 250 docs: self.docs_for_attrs(attrs),
041b39d2 251 sig: sig::item_signature(item, self),
6a06907d 252 attributes: lower_attributes(attrs.to_vec(), self),
7453a54e 253 }))
1a4d82fc 254 }
f035d41b
XL
255 hir::ItemKind::Const(ref typ, _) => {
256 let qualname = format!("::{}", self.tcx.def_path_str(def_id));
13cf67c4 257 filter!(self.span_utils, item.ident.span);
041b39d2 258
f035d41b 259 let id = id_from_def_id(def_id);
13cf67c4 260 let span = self.span_from_span(item.ident.span);
041b39d2
XL
261
262 Some(Data::DefData(Def {
263 kind: DefKind::Const,
264 id,
265 span,
c1a9b12d 266 name: item.ident.to_string(),
041b39d2
XL
267 qualname,
268 value: ty_to_string(typ),
9e0c209e 269 parent: None,
041b39d2
XL
270 children: vec![],
271 decl_id: None,
6a06907d 272 docs: self.docs_for_attrs(attrs),
041b39d2 273 sig: sig::item_signature(item, self),
6a06907d 274 attributes: lower_attributes(attrs.to_vec(), self),
7453a54e 275 }))
85aaf69f 276 }
f035d41b
XL
277 hir::ItemKind::Mod(ref m) => {
278 let qualname = format!("::{}", self.tcx.def_path_str(def_id));
62682a34 279
74b04a01 280 let sm = self.tcx.sess.source_map();
04454e1e 281 let filename = sm.span_to_filename(m.spans.inner_span);
62682a34 282
13cf67c4 283 filter!(self.span_utils, item.ident.span);
32a655c1 284
041b39d2
XL
285 Some(Data::DefData(Def {
286 kind: DefKind::Mod,
f035d41b 287 id: id_from_def_id(def_id),
c1a9b12d 288 name: item.ident.to_string(),
041b39d2 289 qualname,
13cf67c4 290 span: self.span_from_span(item.ident.span),
17df50a5 291 value: filename.prefer_remapped().to_string(),
041b39d2 292 parent: None,
6a06907d
XL
293 children: m
294 .item_ids
295 .iter()
296 .map(|i| id_from_def_id(i.def_id.to_def_id()))
297 .collect(),
041b39d2 298 decl_id: None,
6a06907d 299 docs: self.docs_for_attrs(attrs),
041b39d2 300 sig: sig::item_signature(item, self),
6a06907d 301 attributes: lower_attributes(attrs.to_vec(), self),
7453a54e 302 }))
e9174d1e 303 }
f035d41b 304 hir::ItemKind::Enum(ref def, ref generics) => {
a7813a04 305 let name = item.ident.to_string();
f035d41b 306 let qualname = format!("::{}", self.tcx.def_path_str(def_id));
13cf67c4 307 filter!(self.span_utils, item.ident.span);
f035d41b 308 let value =
04454e1e 309 enum_def_to_string(def, generics, item.ident.name, item.span);
041b39d2
XL
310 Some(Data::DefData(Def {
311 kind: DefKind::Enum,
f035d41b 312 id: id_from_def_id(def_id),
13cf67c4 313 span: self.span_from_span(item.ident.span),
041b39d2
XL
314 name,
315 qualname,
316 value,
317 parent: None,
f035d41b 318 children: def.variants.iter().map(|v| id_from_hir_id(v.id, self)).collect(),
041b39d2 319 decl_id: None,
6a06907d 320 docs: self.docs_for_attrs(attrs),
041b39d2 321 sig: sig::item_signature(item, self),
6a06907d 322 attributes: lower_attributes(attrs.to_vec(), self),
7453a54e 323 }))
e9174d1e 324 }
94222f64
XL
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;
62682a34 331 }
94222f64
XL
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 })
62682a34 370 }
94222f64 371 hir::ItemKind::Impl(_) => None,
d9579d0f
AL
372 _ => {
373 // FIXME
54a0048b 374 bug!();
1a4d82fc
JJ
375 }
376 }
1a4d82fc
JJ
377 }
378
6a06907d 379 pub fn get_field_data(&self, field: &hir::FieldDef<'_>, scope: hir::HirId) -> Option<Def> {
f035d41b
XL
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);
6a06907d 389 let attrs = self.tcx.hir().attrs(field.hir_id);
f035d41b
XL
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,
6a06907d 401 docs: self.docs_for_attrs(attrs),
f035d41b 402 sig: sig::field_signature(field, self),
6a06907d 403 attributes: lower_attributes(attrs.to_vec(), self),
f035d41b 404 })
62682a34
SL
405 }
406
c1a9b12d
SL
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.
f035d41b 409 pub fn get_method_data(&self, hir_id: hir::HirId, ident: Ident, span: Span) -> Option<Def> {
c1a9b12d
SL
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.
f035d41b
XL
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 {
5869c6ff 417 hir::ItemKind::Impl(hir::Impl { ref self_ty, .. }) => {
f035d41b
XL
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![];
6a06907d
XL
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);
f035d41b
XL
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 }
1b1a35ee 445 qualname.push('>');
f035d41b
XL
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) => {
94b46f34
XL
470 let mut docs = String::new();
471 let mut attrs = vec![];
f035d41b 472
6a06907d
XL
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);
94b46f34
XL
476 }
477
f035d41b
XL
478 (
479 format!("::{}", self.tcx.def_path_str(def_id)),
480 Some(def_id),
481 None,
482 docs,
483 attrs,
484 )
94b46f34 485 }
f035d41b
XL
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,
3dfed10e 489 // the typeck results we need might not exist.
f035d41b 490 return None;
c1a9b12d 491 }
abe05a73 492 },
f035d41b 493 };
c1a9b12d 494
13cf67c4 495 let qualname = format!("{}::{}", qualname, ident.name);
c1a9b12d 496
13cf67c4 497 filter!(self.span_utils, ident.span);
32a655c1 498
041b39d2
XL
499 Some(Def {
500 kind: DefKind::Method,
f035d41b 501 id: id_from_def_id(def_id),
13cf67c4
XL
502 span: self.span_from_span(ident.span),
503 name: ident.name.to_string(),
041b39d2 504 qualname,
a7813a04
XL
505 // FIXME you get better data here by using the visitor.
506 value: String::new(),
ba9703b0 507 parent: parent_scope.map(id_from_def_id),
041b39d2 508 children: vec![],
ba9703b0 509 decl_id: decl_id.map(id_from_def_id),
041b39d2
XL
510 docs,
511 sig: None,
512 attributes: lower_attributes(attributes, self),
7453a54e 513 })
c1a9b12d
SL
514 }
515
f035d41b 516 pub fn get_expr_data(&self, expr: &hir::Expr<'_>) -> Option<Data> {
3dfed10e 517 let ty = self.typeck_results().expr_ty_adjusted_opt(expr)?;
1b1a35ee 518 if matches!(ty.kind(), ty::Error(_)) {
7453a54e
SL
519 return None;
520 }
e74abb32 521 match expr.kind {
f035d41b 522 hir::ExprKind::Field(ref sub_ex, ident) => {
1b1a35ee 523 match self.typeck_results().expr_ty_adjusted(&sub_ex).kind() {
b7449926 524 ty::Adt(def, _) if !def.is_enum() => {
83c7162d 525 let variant = &def.non_enum_variant();
13cf67c4
XL
526 filter!(self.span_utils, ident.span);
527 let span = self.span_from_span(ident.span);
ba9703b0 528 Some(Data::RefData(Ref {
041b39d2
XL
529 kind: RefKind::Variable,
530 span,
74b04a01
XL
531 ref_id: self
532 .tcx
533 .find_field_index(ident, variant)
534 .map(|index| id_from_def_id(variant.fields[index].did))
ba9703b0
XL
535 .unwrap_or_else(null_id),
536 }))
62682a34 537 }
b7449926 538 ty::Tuple(..) => None,
62682a34 539 _ => {
416331ca 540 debug!("expected struct or union type, found {:?}", ty);
62682a34
SL
541 None
542 }
543 }
544 }
1b1a35ee 545 hir::ExprKind::Struct(qpath, ..) => match ty.kind() {
3dfed10e
XL
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,
5e7ed085 553 ref_id: id_from_def_id(def.did()),
3dfed10e 554 }))
62682a34 555 }
3dfed10e
XL
556 _ => {
557 debug!("expected adt, found {:?}", ty);
558 None
559 }
560 },
f035d41b 561 hir::ExprKind::MethodCall(ref seg, ..) => {
5e7ed085
FG
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;
abe05a73 565 };
476ff2be 566 let (def_id, decl_id) = match self.tcx.associated_item(method_id).container {
064997fb
FG
567 ty::ImplContainer => (Some(method_id), None),
568 ty::TraitContainer => (None, Some(method_id)),
c1a9b12d 569 };
83c7162d 570 let sub_span = seg.ident.span;
13cf67c4 571 filter!(self.span_utils, sub_span);
abe05a73 572 let span = self.span_from_span(sub_span);
041b39d2
XL
573 Some(Data::RefData(Ref {
574 kind: RefKind::Function,
575 span,
ba9703b0 576 ref_id: def_id.or(decl_id).map(id_from_def_id).unwrap_or_else(null_id),
c1a9b12d
SL
577 }))
578 }
f035d41b
XL
579 hir::ExprKind::Path(ref path) => {
580 self.get_path_data(expr.hir_id, path).map(Data::RefData)
c1a9b12d 581 }
62682a34
SL
582 _ => {
583 // FIXME
f035d41b 584 bug!("invalid expression: {:?}", expr);
62682a34
SL
585 }
586 }
587 }
588
f035d41b 589 pub fn get_path_res(&self, hir_id: hir::HirId) -> Res {
dc9dc135 590 match self.tcx.hir().get(hir_id) {
48663c56 591 Node::TraitRef(tr) => tr.path.res,
476ff2be 592
dfeec247 593 Node::Item(&hir::Item { kind: hir::ItemKind::Use(path, _), .. }) => path.res,
dfeec247
XL
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);
f035d41b 598 self.get_path_res(parent_node)
0731742a 599 }
dfeec247 600 },
9fa01778 601
dfeec247 602 Node::Expr(&hir::Expr { kind: hir::ExprKind::Struct(ref qpath, ..), .. }) => {
3dfed10e 603 self.typeck_results().qpath_res(qpath, hir_id)
9fa01778
XL
604 }
605
dfeec247 606 Node::Expr(&hir::Expr { kind: hir::ExprKind::Path(ref qpath), .. })
ba9703b0
XL
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 })
f035d41b
XL
614 | Node::Ty(&hir::Ty { kind: hir::TyKind::Path(ref qpath), .. }) => match qpath {
615 hir::QPath::Resolved(_, path) => path.res,
29967ef6
XL
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 }
f035d41b 624 },
476ff2be 625
064997fb
FG
626 Node::Pat(&hir::Pat { kind: hir::PatKind::Binding(_, canonical_id, ..), .. }) => {
627 Res::Local(canonical_id)
628 }
476ff2be 629
48663c56 630 _ => Res::Err,
476ff2be
SL
631 }
632 }
633
f035d41b
XL
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),
3dfed10e 638 hir::QPath::LangItem(..) => None,
f035d41b
XL
639 };
640 segment.and_then(|seg| {
dfeec247
XL
641 self.get_path_segment_data(seg).or_else(|| self.get_path_segment_data_with_id(seg, id))
642 })
13cf67c4
XL
643 }
644
f035d41b
XL
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?)
13cf67c4
XL
647 }
648
f035d41b 649 pub fn get_path_segment_data_with_id(
13cf67c4 650 &self,
f035d41b
XL
651 path_seg: &hir::PathSegment<'_>,
652 id: hir::HirId,
13cf67c4 653 ) -> Option<Ref> {
abe05a73 654 // Returns true if the path is function type sugar, e.g., `Fn(A) -> B`.
f035d41b 655 fn fn_type(seg: &hir::PathSegment<'_>) -> bool {
5869c6ff 656 seg.args.map_or(false, |args| args.parenthesized)
abe05a73
XL
657 }
658
48663c56 659 let res = self.get_path_res(id);
13cf67c4
XL
660 let span = path_seg.ident.span;
661 filter!(self.span_utils, span);
662 let span = self.span_from_span(span);
663
48663c56 664 match res {
f035d41b
XL
665 Res::Local(id) => {
666 Some(Ref { kind: RefKind::Variable, span, ref_id: id_from_hir_id(id, self) })
667 }
48663c56 668 Res::Def(HirDefKind::Trait, def_id) if fn_type(path_seg) => {
dfeec247 669 Some(Ref { kind: RefKind::Type, span, ref_id: id_from_def_id(def_id) })
abe05a73 670 }
ba9703b0
XL
671 Res::Def(
672 HirDefKind::Struct
673 | HirDefKind::Variant
674 | HirDefKind::Union
675 | HirDefKind::Enum
676 | HirDefKind::TyAlias
677 | HirDefKind::ForeignTy
678 | HirDefKind::TraitAlias
ba9703b0
XL
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) }),
48663c56 685 Res::Def(HirDefKind::ConstParam, def_id) => {
dfeec247 686 Some(Ref { kind: RefKind::Variable, span, ref_id: id_from_def_id(def_id) })
9fa01778 687 }
3dfed10e 688 Res::Def(HirDefKind::Ctor(..), def_id) => {
f035d41b 689 // This is a reference to a tuple struct or an enum variant where the def_id points
abe05a73 690 // to an invisible constructor function. That is not a very useful
f035d41b 691 // def, so adjust to point to the tuple struct or enum variant itself.
04454e1e 692 let parent_def_id = self.tcx.parent(def_id);
dfeec247 693 Some(Ref { kind: RefKind::Type, span, ref_id: id_from_def_id(parent_def_id) })
abe05a73 694 }
5e7ed085 695 Res::Def(HirDefKind::Static(_) | HirDefKind::Const | HirDefKind::AssocConst, _) => {
f035d41b
XL
696 Some(Ref { kind: RefKind::Variable, span, ref_id: id_from_def_id(res.def_id()) })
697 }
ba9703b0 698 Res::Def(HirDefKind::AssocFn, decl_id) => {
e9174d1e 699 let def_id = if decl_id.is_local() {
064997fb 700 if self.tcx.impl_defaultness(decl_id).has_value() {
5099ac24
FG
701 Some(decl_id)
702 } else {
703 None
704 }
c1a9b12d
SL
705 } else {
706 None
707 };
041b39d2
XL
708 Some(Ref {
709 kind: RefKind::Function,
710 span,
711 ref_id: id_from_def_id(def_id.unwrap_or(decl_id)),
712 })
e9174d1e 713 }
48663c56 714 Res::Def(HirDefKind::Fn, def_id) => {
dfeec247 715 Some(Ref { kind: RefKind::Function, span, ref_id: id_from_def_id(def_id) })
c1a9b12d 716 }
48663c56 717 Res::Def(HirDefKind::Mod, def_id) => {
dfeec247 718 Some(Ref { kind: RefKind::Mod, span, ref_id: id_from_def_id(def_id) })
c1a9b12d 719 }
f9f354fc
XL
720
721 Res::Def(
722 HirDefKind::Macro(..)
723 | HirDefKind::ExternCrate
724 | HirDefKind::ForeignMod
725 | HirDefKind::LifetimeParam
726 | HirDefKind::AnonConst
3c0e092e 727 | HirDefKind::InlineConst
f9f354fc
XL
728 | HirDefKind::Use
729 | HirDefKind::Field
730 | HirDefKind::GlobalAsm
731 | HirDefKind::Impl
732 | HirDefKind::Closure
733 | HirDefKind::Generator,
734 _,
735 )
736 | Res::PrimTy(..)
5099ac24 737 | Res::SelfTy { .. }
dfeec247
XL
738 | Res::ToolMod
739 | Res::NonMacroAttr(..)
740 | Res::SelfCtor(..)
741 | Res::Err => None,
c1a9b12d
SL
742 }
743 }
744
abe05a73
XL
745 pub fn get_field_ref_data(
746 &self,
6a06907d 747 field_ref: &hir::ExprField<'_>,
abe05a73
XL
748 variant: &ty::VariantDef,
749 ) -> Option<Ref> {
13cf67c4
XL
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);
dfeec247 753 Ref { kind: RefKind::Variable, span, ref_id: id_from_def_id(variant.fields[index].did) }
7453a54e
SL
754 })
755 }
756
041b39d2 757 /// Attempt to return MacroRef for any AST node.
7453a54e
SL
758 ///
759 /// For a given piece of AST defined by the supplied Span and NodeId,
9fa01778 760 /// returns `None` if the node is not macro-generated or the span is malformed,
041b39d2 761 /// else uses the expansion callsite and callee to return some MacroRef.
cdc7bbd5
XL
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> {
7453a54e
SL
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.
cc61c64b 772 let callsite = span.source_callsite();
041b39d2 773 let callsite_span = self.span_from_span(callsite);
abe05a73 774 let callee = span.source_callee()?;
7453a54e 775
dfeec247 776 let mac_name = match callee.kind {
136023e0 777 ExpnKind::Macro(kind, name) => match kind {
dfeec247
XL
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?
29967ef6
XL
787 ExpnKind::Inlined | ExpnKind::Root | ExpnKind::AstPass(_) | ExpnKind::Desugaring(_) => {
788 return None;
789 }
dfeec247 790 };
7453a54e 791
416331ca 792 let callee_span = self.span_from_span(callee.def_site);
041b39d2
XL
793 Some(MacroRef {
794 span: callsite_span,
dfeec247 795 qualname: mac_name.to_string(), // FIXME: generate the real qualname
041b39d2 796 callee_span,
7453a54e 797 })
62682a34
SL
798 }
799
f035d41b 800 fn lookup_def_id(&self, ref_id: hir::HirId) -> Option<DefId> {
48663c56 801 match self.get_path_res(ref_id) {
5099ac24 802 Res::PrimTy(_) | Res::SelfTy { .. } | Res::Err => None,
74b04a01 803 def => def.opt_def_id(),
62682a34
SL
804 }
805 }
806
f035d41b 807 fn docs_for_attrs(&self, attrs: &[ast::Attribute]) -> String {
3b2f2976
XL
808 let mut result = String::new();
809
810 for attr in attrs {
5099ac24 811 if let Some((val, kind)) = attr.doc_str_and_comment_kind() {
3dfed10e 812 // FIXME: Should save-analysis beautify doc strings itself or leave it to users?
5099ac24 813 result.push_str(beautify_doc_string(val, kind).as_str());
dfeec247 814 result.push('\n');
3b2f2976
XL
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
c1a9b12d 825 }
2c00a5a8
XL
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 }
d9579d0f 832}
1a4d82fc 833
abe05a73
XL
834// An AST visitor for collecting paths (e.g., the names of structs) and formal
835// variables (idents) from patterns.
836struct PathCollector<'l> {
f035d41b
XL
837 tcx: TyCtxt<'l>,
838 collected_paths: Vec<(hir::HirId, &'l hir::QPath<'l>)>,
839 collected_idents: Vec<(hir::HirId, Ident, hir::Mutability)>,
d9579d0f 840}
1a4d82fc 841
abe05a73 842impl<'l> PathCollector<'l> {
f035d41b
XL
843 fn new(tcx: TyCtxt<'l>) -> PathCollector<'l> {
844 PathCollector { tcx, collected_paths: vec![], collected_idents: vec![] }
1a4d82fc 845 }
d9579d0f 846}
1a4d82fc 847
dc9dc135 848impl<'l> Visitor<'l> for PathCollector<'l> {
5099ac24 849 type NestedFilter = nested_filter::All;
f035d41b 850
5099ac24
FG
851 fn nested_visit_map(&mut self) -> Self::Map {
852 self.tcx.hir()
f035d41b
XL
853 }
854
855 fn visit_pat(&mut self, p: &'l hir::Pat<'l>) {
e74abb32 856 match p.kind {
f035d41b
XL
857 hir::PatKind::Struct(ref path, ..) => {
858 self.collected_paths.push((p.hir_id, path));
1a4d82fc 859 }
f035d41b
XL
860 hir::PatKind::TupleStruct(ref path, ..) | hir::PatKind::Path(ref path) => {
861 self.collected_paths.push((p.hir_id, path));
1a4d82fc 862 }
f035d41b 863 hir::PatKind::Binding(bm, _, ident, _) => {
abe05a73
XL
864 debug!(
865 "PathCollector, visit ident in pat {}: {:?} {:?}",
dfeec247 866 ident, p.span, ident.span
abe05a73 867 );
1a4d82fc
JJ
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.
f035d41b
XL
872 hir::BindingAnnotation::Unannotated | hir::BindingAnnotation::Ref => {
873 hir::Mutability::Not
874 }
875 hir::BindingAnnotation::Mutable | hir::BindingAnnotation::RefMut => {
876 hir::Mutability::Mut
877 }
1a4d82fc 878 };
f035d41b 879 self.collected_idents.push((p.hir_id, ident, immut));
1a4d82fc 880 }
d9579d0f 881 _ => {}
1a4d82fc 882 }
f035d41b 883 intravisit::walk_pat(self, p);
1a4d82fc
JJ
884 }
885}
886
cc61c64b
XL
887/// Defines what to do with the results of saving the analysis.
888pub trait SaveHandler {
f035d41b 889 fn save(&mut self, save_ctxt: &SaveContext<'_>, analysis: &Analysis);
cc61c64b 890}
9cc50fc6 891
cc61c64b
XL
892/// Dump the save-analysis results to a file.
893pub struct DumpHandler<'a> {
cc61c64b 894 odir: Option<&'a Path>,
abe05a73 895 cratename: String,
cc61c64b 896}
1a4d82fc 897
cc61c64b 898impl<'a> DumpHandler<'a> {
3b2f2976 899 pub fn new(odir: Option<&'a Path>, cratename: &str) -> DumpHandler<'a> {
dfeec247 900 DumpHandler { odir, cratename: cratename.to_owned() }
cc61c64b 901 }
1a4d82fc 902
f035d41b 903 fn output_file(&self, ctx: &SaveContext<'_>) -> (BufWriter<File>, PathBuf) {
3b2f2976
XL
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 };
cc61c64b 912
3b2f2976
XL
913 if let Err(e) = std::fs::create_dir_all(&root_path) {
914 error!("Could not create directory {}: {}", root_path.display(), e);
915 }
cc61c64b 916
f9f354fc 917 let executable = sess.crate_types().iter().any(|ct| *ct == CrateType::Executable);
dfeec247 918 let mut out_name = if executable { String::new() } else { "lib".to_owned() };
3b2f2976
XL
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);
cc61c64b 923
3b2f2976
XL
924 root_path
925 }
cc61c64b 926 };
3b2f2976
XL
927
928 info!("Writing output to {}", file_name.display());
929
dfeec247
XL
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 }));
3b2f2976 933
dc9dc135 934 (output_file, file_name)
cc61c64b
XL
935 }
936}
937
416331ca 938impl SaveHandler for DumpHandler<'_> {
f035d41b 939 fn save(&mut self, save_ctxt: &SaveContext<'_>, analysis: &Analysis) {
dc9dc135 940 let sess = &save_ctxt.tcx.sess;
416331ca
XL
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 }
dc9dc135 945
416331ca 946 if sess.opts.json_artifact_notifications {
dfeec247 947 sess.parse_sess.span_diagnostic.emit_artifact_notification(&file_name, "save-analysis");
dc9dc135 948 }
1a4d82fc 949 }
cc61c64b
XL
950}
951
952/// Call a callback with the results of save-analysis.
953pub struct CallbackHandler<'b> {
8faf50e0 954 pub callback: &'b mut dyn FnMut(&rls_data::Analysis),
cc61c64b
XL
955}
956
416331ca 957impl SaveHandler for CallbackHandler<'_> {
f035d41b 958 fn save(&mut self, _: &SaveContext<'_>, analysis: &Analysis) {
416331ca 959 (self.callback)(analysis)
1a4d82fc 960 }
cc61c64b 961}
1a4d82fc 962
abe05a73 963pub fn process_crate<'l, 'tcx, H: SaveHandler>(
dc9dc135 964 tcx: TyCtxt<'tcx>,
abe05a73 965 cratename: &str,
0bf4aa26 966 input: &'l Input,
abe05a73
XL
967 config: Option<Config>,
968 mut handler: H,
969) {
5e7ed085 970 with_no_trimmed_paths!({
1b1a35ee
XL
971 tcx.dep_graph.with_ignore(|| {
972 info!("Dumping crate {}", cratename);
973
5099ac24 974 // Privacy checking must be done outside of type inference; use a
1b1a35ee
XL
975 // fallback in case the access levels couldn't have been correctly computed.
976 let access_levels = match tcx.sess.compile_status() {
17df50a5 977 Ok(..) => tcx.privacy_access_levels(()),
1b1a35ee
XL
978 Err(..) => tcx.arena.alloc(AccessLevels::default()),
979 };
0731742a 980
1b1a35ee
XL
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 };
1a4d82fc 989
1b1a35ee 990 let mut visitor = DumpVisitor::new(save_ctxt);
416331ca 991
c295e0f8 992 visitor.dump_crate_info(cratename);
1b1a35ee 993 visitor.dump_compilation_options(input, cratename);
c295e0f8 994 visitor.process_crate();
416331ca 995
1b1a35ee
XL
996 handler.save(&visitor.save_ctxt, &visitor.analysis())
997 })
2c00a5a8 998 })
1a4d82fc 999}
d9579d0f 1000
3b2f2976
XL
1001fn find_config(supplied: Option<Config>) -> Config {
1002 if let Some(config) = supplied {
1003 return config;
1004 }
48663c56 1005
3b2f2976 1006 match env::var_os("RUST_SAVE_ANALYSIS_CONFIG") {
3b2f2976 1007 None => Config::default(),
dfeec247
XL
1008 Some(config) => config
1009 .to_str()
48663c56
XL
1010 .ok_or(())
1011 .map_err(|_| error!("`RUST_SAVE_ANALYSIS_CONFIG` isn't UTF-8"))
dfeec247
XL
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(),
3b2f2976
XL
1017 }
1018}
1019
d9579d0f
AL
1020// Utility functions for the module.
1021
1022// Helper function to escape quotes in a string
1023fn escape(s: String) -> String {
a2a8927a 1024 s.replace('\"', "\"\"")
d9579d0f
AL
1025}
1026
7453a54e
SL
1027// Helper function to determine if a span came from a
1028// macro expansion or syntax extension.
041b39d2 1029fn generated_code(span: Span) -> bool {
e1599b0c 1030 span.from_expansion() || span.is_dummy()
d9579d0f 1031}
041b39d2
XL
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.
1035fn id_from_def_id(id: DefId) -> rls_data::Id {
dfeec247 1036 rls_data::Id { krate: id.krate.as_u32(), index: id.index.as_u32() }
041b39d2
XL
1037}
1038
f035d41b
XL
1039fn id_from_hir_id(id: hir::HirId, scx: &SaveContext<'_>) -> rls_data::Id {
1040 let def_id = scx.tcx.hir().opt_local_def_id(id);
ba9703b0 1041 def_id.map(|id| id_from_def_id(id.to_def_id())).unwrap_or_else(|| {
f035d41b
XL
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 }
ea8adc8c 1050 })
041b39d2
XL
1051}
1052
1053fn null_id() -> rls_data::Id {
f035d41b 1054 rls_data::Id { krate: u32::MAX, index: u32::MAX }
041b39d2
XL
1055}
1056
f035d41b 1057fn lower_attributes(attrs: Vec<ast::Attribute>, scx: &SaveContext<'_>) -> Vec<rls_data::Attribute> {
dfeec247
XL
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;
f035d41b 1067 let value = attribute_to_string(&attr);
dfeec247
XL
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()
041b39d2 1075}