]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_metadata/src/rmeta/decoder.rs
New upstream version 1.78.0+dfsg1
[rustc.git] / compiler / rustc_metadata / src / rmeta / decoder.rs
CommitLineData
223e47cc
LB
1// Decoding metadata from a single crate's metadata
2
4b012472 3use crate::creader::CStore;
353b0b11 4use crate::rmeta::table::IsDefault;
dfeec247 5use crate::rmeta::*;
9e0c209e 6
3dfed10e 7use rustc_ast as ast;
dfeec247 8use rustc_data_structures::captures::Captures;
c0240ec0 9use rustc_data_structures::fingerprint::Fingerprint;
49aad941 10use rustc_data_structures::owned_slice::OwnedSlice;
c0240ec0 11use rustc_data_structures::sync::{Lock, Lrc, OnceLock};
5869c6ff 12use rustc_data_structures::unhash::UnhashMap;
ba9703b0 13use rustc_expand::base::{SyntaxExtension, SyntaxExtensionKind};
923072b8 14use rustc_expand::proc_macro::{AttrProcMacro, BangProcMacro, DeriveProcMacro};
4b012472 15use rustc_hir::def::Res;
c620b35d 16use rustc_hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE};
4b012472 17use rustc_hir::definitions::{DefPath, DefPathData};
c295e0f8 18use rustc_hir::diagnostic_items::DiagnosticItems;
4b012472
FG
19use rustc_index::Idx;
20use rustc_middle::middle::lib_features::LibFeatures;
ba9703b0 21use rustc_middle::mir::interpret::{AllocDecodingSession, AllocDecodingState};
ba9703b0 22use rustc_middle::ty::codec::TyDecoder;
4b012472 23use rustc_middle::ty::Visibility;
923072b8
FG
24use rustc_serialize::opaque::MemDecoder;
25use rustc_serialize::{Decodable, Decoder};
4b012472 26use rustc_session::cstore::{CrateSource, ExternCrate};
ba9703b0 27use rustc_session::Session;
4b012472 28use rustc_span::symbol::kw;
c0240ec0 29use rustc_span::{BytePos, Pos, SpanData, SpanDecoder, SyntaxContext, DUMMY_SP};
9cc50fc6 30
ba9703b0 31use proc_macro::bridge::client::ProcMacro;
923072b8 32use std::iter::TrustedLen;
ba9703b0 33use std::path::Path;
487cf647 34use std::{io, iter, mem};
223e47cc 35
a2a8927a 36pub(super) use cstore_impl::provide;
3dfed10e 37use rustc_span::hygiene::HygieneDecodeContext;
60c5eb7d
XL
38
39mod cstore_impl;
40
c295e0f8
XL
41/// A reference to the raw binary version of crate metadata.
42/// A `MetadataBlob` internally is just a reference counted pointer to
43/// the actual data, so cloning it is cheap.
44#[derive(Clone)]
49aad941 45pub(crate) struct MetadataBlob(pub(crate) OwnedSlice);
c295e0f8 46
c295e0f8
XL
47impl std::ops::Deref for MetadataBlob {
48 type Target = [u8];
49
50 #[inline]
51 fn deref(&self) -> &[u8] {
52 &self.0[..]
53 }
54}
60c5eb7d 55
487cf647
FG
56/// A map from external crate numbers (as decoded from some crate file) to
57/// local crate numbers (as generated during this session). Each external
58/// crate may refer to types in other external crates, and each has their
59/// own crate numbers.
923072b8 60pub(crate) type CrateNumMap = IndexVec<CrateNum, CrateNum>;
60c5eb7d 61
923072b8 62pub(crate) struct CrateMetadata {
60c5eb7d
XL
63 /// The primary crate data - binary metadata blob.
64 blob: MetadataBlob,
65
66 // --- Some data pre-decoded from the metadata blob, usually for performance ---
fe692bf9 67 /// Data about the top-level items in a crate, as well as various crate-level metadata.
923072b8 68 root: CrateRoot,
60c5eb7d
XL
69 /// Trait impl data.
70 /// FIXME: Used only from queries and can use query cache,
71 /// so pre-decoding can probably be avoided.
923072b8 72 trait_impls: FxHashMap<(u32, DefIndex), LazyArray<(DefIndex, Option<SimplifiedType>)>>,
5e7ed085
FG
73 /// Inherent impls which do not follow the normal coherence rules.
74 ///
75 /// These can be introduced using either `#![rustc_coherence_is_core]`
76 /// or `#[rustc_allow_incoherent_impl]`.
923072b8 77 incoherent_impls: FxHashMap<SimplifiedType, LazyArray<DefIndex>>,
60c5eb7d
XL
78 /// Proc macro descriptions for this crate, if it's a proc macro crate.
79 raw_proc_macros: Option<&'static [ProcMacro]>,
80 /// Source maps for code from the crate.
f2b60f7d 81 source_map_import_info: Lock<Vec<Option<ImportedSourceFile>>>,
c295e0f8
XL
82 /// For every definition in this crate, maps its `DefPathHash` to its `DefIndex`.
83 def_path_hash_map: DefPathHashMapRef<'static>,
136023e0 84 /// Likewise for ExpnHash.
781aab86 85 expn_hash_map: OnceLock<UnhashMap<ExpnHash, ExpnIndex>>,
60c5eb7d
XL
86 /// Used for decoding interpret::AllocIds in a cached & thread-safe manner.
87 alloc_decoding_state: AllocDecodingState,
3dfed10e
XL
88 /// Caches decoded `DefKey`s.
89 def_key_cache: Lock<FxHashMap<DefIndex, DefKey>>,
60c5eb7d
XL
90
91 // --- Other significant crate properties ---
60c5eb7d
XL
92 /// ID of this crate, from the current compilation session's point of view.
93 cnum: CrateNum,
94 /// Maps crate IDs as they are were seen from this crate's compilation sessions into
95 /// IDs as they are seen from the current compilation session.
96 cnum_map: CrateNumMap,
97 /// Same ID set as `cnum_map` plus maybe some injected crates like panic runtime.
c0240ec0 98 dependencies: Vec<CrateNum>,
60c5eb7d 99 /// How to link (or not link) this crate to the currently compiled crate.
c0240ec0 100 dep_kind: CrateDepKind,
60c5eb7d 101 /// Filesystem location of this crate.
5099ac24 102 source: Lrc<CrateSource>,
fe692bf9
FG
103 /// Whether or not this crate should be consider a private dependency.
104 /// Used by the 'exported_private_dependencies' lint, and for determining
105 /// whether to emit suggestions that reference this crate.
c0240ec0 106 private_dep: bool,
60c5eb7d
XL
107 /// The hash for the host proc macro. Used to support `-Z dual-proc-macro`.
108 host_hash: Option<Svh>,
c620b35d
FG
109 /// The crate was used non-speculatively.
110 used: bool,
60c5eb7d 111
3dfed10e
XL
112 /// Additional data used for decoding `HygieneData` (e.g. `SyntaxContext`
113 /// and `ExpnId`).
49aad941 114 /// Note that we store a `HygieneDecodeContext` for each `CrateMetadata`. This is
3dfed10e
XL
115 /// because `SyntaxContext` ids are not globally unique, so we need
116 /// to track which ids we've decoded on a per-crate basis.
117 hygiene_context: HygieneDecodeContext,
118
60c5eb7d 119 // --- Data used only for improving diagnostics ---
60c5eb7d
XL
120 /// Information about the `extern crate` item or path that caused this crate to be loaded.
121 /// If this is `None`, then the crate was injected (e.g., by the allocator).
c0240ec0 122 extern_crate: Option<ExternCrate>,
60c5eb7d
XL
123}
124
dfeec247 125/// Holds information about a rustc_span::SourceFile imported from another crate.
f2b60f7d
FG
126/// See `imported_source_file()` for more information.
127#[derive(Clone)]
60c5eb7d
XL
128struct ImportedSourceFile {
129 /// This SourceFile's byte-offset within the source_map of its original crate
dfeec247 130 original_start_pos: rustc_span::BytePos,
60c5eb7d 131 /// The end of this SourceFile within the source_map of its original crate
dfeec247 132 original_end_pos: rustc_span::BytePos,
60c5eb7d 133 /// The imported SourceFile's representation within the local source_map
dfeec247 134 translated_source_file: Lrc<rustc_span::SourceFile>,
60c5eb7d
XL
135}
136
137pub(super) struct DecodeContext<'a, 'tcx> {
923072b8 138 opaque: MemDecoder<'a>,
74b04a01 139 cdata: Option<CrateMetadataRef<'a>>,
c295e0f8 140 blob: &'a MetadataBlob,
dc9dc135
XL
141 sess: Option<&'tcx Session>,
142 tcx: Option<TyCtxt<'tcx>>,
c34b1796 143
c30ab7b3 144 lazy_state: LazyState,
0531ce1d 145
94b46f34
XL
146 // Used for decoding interpret::AllocIds in a cached & thread-safe manner.
147 alloc_decoding_session: Option<AllocDecodingSession<'a>>,
223e47cc
LB
148}
149
9e0c209e 150/// Abstract over the various ways one can create metadata decoders.
60c5eb7d 151pub(super) trait Metadata<'a, 'tcx>: Copy {
c295e0f8
XL
152 fn blob(self) -> &'a MetadataBlob;
153
74b04a01 154 fn cdata(self) -> Option<CrateMetadataRef<'a>> {
dfeec247
XL
155 None
156 }
157 fn sess(self) -> Option<&'tcx Session> {
158 None
159 }
160 fn tcx(self) -> Option<TyCtxt<'tcx>> {
161 None
162 }
b039eaaf 163
9e0c209e 164 fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> {
476ff2be 165 let tcx = self.tcx();
9e0c209e 166 DecodeContext {
923072b8 167 opaque: MemDecoder::new(self.blob(), pos),
9e0c209e 168 cdata: self.cdata(),
c295e0f8 169 blob: self.blob(),
476ff2be 170 sess: self.sess().or(tcx.map(|tcx| tcx.sess)),
3b2f2976 171 tcx,
c30ab7b3 172 lazy_state: LazyState::NoNode,
dfeec247
XL
173 alloc_decoding_session: self
174 .cdata()
74b04a01 175 .map(|cdata| cdata.cdata.alloc_decoding_state.new_decoding_session()),
9e0c209e
SL
176 }
177 }
b039eaaf
SL
178}
179
9e0c209e 180impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a MetadataBlob {
c295e0f8
XL
181 #[inline]
182 fn blob(self) -> &'a MetadataBlob {
183 self
9e0c209e 184 }
223e47cc
LB
185}
186
dc9dc135 187impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a MetadataBlob, &'tcx Session) {
c295e0f8
XL
188 #[inline]
189 fn blob(self) -> &'a MetadataBlob {
190 self.0
abe05a73
XL
191 }
192
c295e0f8 193 #[inline]
dc9dc135 194 fn sess(self) -> Option<&'tcx Session> {
abe05a73
XL
195 let (_, sess) = self;
196 Some(sess)
197 }
198}
199
5099ac24 200impl<'a, 'tcx> Metadata<'a, 'tcx> for CrateMetadataRef<'a> {
c295e0f8
XL
201 #[inline]
202 fn blob(self) -> &'a MetadataBlob {
5099ac24 203 &self.cdata.blob
c30ab7b3 204 }
c295e0f8 205 #[inline]
74b04a01 206 fn cdata(self) -> Option<CrateMetadataRef<'a>> {
5099ac24 207 Some(self)
c30ab7b3 208 }
a7813a04
XL
209}
210
5099ac24 211impl<'a, 'tcx> Metadata<'a, 'tcx> for (CrateMetadataRef<'a>, &'tcx Session) {
c295e0f8
XL
212 #[inline]
213 fn blob(self) -> &'a MetadataBlob {
5099ac24 214 &self.0.cdata.blob
476ff2be 215 }
c295e0f8 216 #[inline]
74b04a01 217 fn cdata(self) -> Option<CrateMetadataRef<'a>> {
5099ac24 218 Some(self.0)
476ff2be 219 }
c295e0f8 220 #[inline]
dc9dc135 221 fn sess(self) -> Option<&'tcx Session> {
5099ac24 222 Some(self.1)
476ff2be
SL
223 }
224}
225
5099ac24 226impl<'a, 'tcx> Metadata<'a, 'tcx> for (CrateMetadataRef<'a>, TyCtxt<'tcx>) {
c295e0f8
XL
227 #[inline]
228 fn blob(self) -> &'a MetadataBlob {
5099ac24 229 &self.0.cdata.blob
c30ab7b3 230 }
c295e0f8 231 #[inline]
74b04a01 232 fn cdata(self) -> Option<CrateMetadataRef<'a>> {
5099ac24 233 Some(self.0)
c30ab7b3 234 }
c295e0f8 235 #[inline]
dc9dc135 236 fn tcx(self) -> Option<TyCtxt<'tcx>> {
c30ab7b3
SL
237 Some(self.1)
238 }
223e47cc
LB
239}
240
923072b8 241impl<T: ParameterizedOverTcx> LazyValue<T> {
781aab86 242 #[inline]
923072b8
FG
243 fn decode<'a, 'tcx, M: Metadata<'a, 'tcx>>(self, metadata: M) -> T::Value<'tcx>
244 where
245 T::Value<'tcx>: Decodable<DecodeContext<'a, 'tcx>>,
246 {
e74abb32 247 let mut dcx = metadata.decoder(self.position.get());
9e0c209e 248 dcx.lazy_state = LazyState::NodeStart(self.position);
923072b8 249 T::Value::decode(&mut dcx)
62682a34
SL
250 }
251}
252
923072b8
FG
253struct DecodeIterator<'a, 'tcx, T> {
254 elem_counter: std::ops::Range<usize>,
255 dcx: DecodeContext<'a, 'tcx>,
256 _phantom: PhantomData<fn() -> T>,
04454e1e
FG
257}
258
923072b8
FG
259impl<'a, 'tcx, T: Decodable<DecodeContext<'a, 'tcx>>> Iterator for DecodeIterator<'a, 'tcx, T> {
260 type Item = T;
5e7ed085 261
923072b8
FG
262 #[inline(always)]
263 fn next(&mut self) -> Option<Self::Item> {
264 self.elem_counter.next().map(|_| T::decode(&mut self.dcx))
5e7ed085 265 }
5e7ed085 266
923072b8
FG
267 #[inline(always)]
268 fn size_hint(&self) -> (usize, Option<usize>) {
269 self.elem_counter.size_hint()
5e7ed085
FG
270 }
271}
272
923072b8
FG
273impl<'a, 'tcx, T: Decodable<DecodeContext<'a, 'tcx>>> ExactSizeIterator
274 for DecodeIterator<'a, 'tcx, T>
5e7ed085 275{
923072b8
FG
276 fn len(&self) -> usize {
277 self.elem_counter.len()
5e7ed085
FG
278 }
279}
280
923072b8
FG
281unsafe impl<'a, 'tcx, T: Decodable<DecodeContext<'a, 'tcx>>> TrustedLen
282 for DecodeIterator<'a, 'tcx, T>
5e7ed085 283{
5e7ed085
FG
284}
285
923072b8 286impl<T: ParameterizedOverTcx> LazyArray<T> {
781aab86 287 #[inline]
923072b8 288 fn decode<'a, 'tcx, M: Metadata<'a, 'tcx>>(
5e7ed085 289 self,
923072b8
FG
290 metadata: M,
291 ) -> DecodeIterator<'a, 'tcx, T::Value<'tcx>>
292 where
293 T::Value<'tcx>: Decodable<DecodeContext<'a, 'tcx>>,
294 {
295 let mut dcx = metadata.decoder(self.position.get());
296 dcx.lazy_state = LazyState::NodeStart(self.position);
297 DecodeIterator { elem_counter: (0..self.num_elems), dcx, _phantom: PhantomData }
04454e1e
FG
298 }
299}
300
9e0c209e 301impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
c295e0f8 302 #[inline]
e74abb32 303 fn tcx(&self) -> TyCtxt<'tcx> {
353b0b11 304 let Some(tcx) = self.tcx else {
add651ee
FG
305 bug!(
306 "No TyCtxt found for decoding. \
307 You need to explicitly pass `(crate_metadata_ref, tcx)` to `decode` instead of just `crate_metadata_ref`."
308 );
353b0b11
FG
309 };
310 tcx
c295e0f8
XL
311 }
312
313 #[inline]
314 pub fn blob(&self) -> &'a MetadataBlob {
315 self.blob
9e0c209e 316 }
223e47cc 317
c295e0f8
XL
318 #[inline]
319 pub fn cdata(&self) -> CrateMetadataRef<'a> {
320 debug_assert!(self.cdata.is_some(), "missing CrateMetadata in DecodeContext");
321 self.cdata.unwrap()
9e0c209e 322 }
a7813a04 323
04454e1e 324 #[inline]
17df50a5 325 fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum {
04454e1e 326 self.cdata().map_encoded_cnum_to_current(cnum)
17df50a5
XL
327 }
328
923072b8 329 #[inline]
c620b35d 330 fn read_lazy_offset_then<T>(&mut self, f: impl Fn(NonZero<usize>) -> T) -> T {
5099ac24 331 let distance = self.read_usize();
9e0c209e 332 let position = match self.lazy_state {
e1599b0c 333 LazyState::NoNode => bug!("read_lazy_with_meta: outside of a metadata node"),
9e0c209e 334 LazyState::NodeStart(start) => {
e74abb32 335 let start = start.get();
5099ac24
FG
336 assert!(distance <= start);
337 start - distance
9e0c209e 338 }
5099ac24 339 LazyState::Previous(last_pos) => last_pos.get() + distance,
9e0c209e 340 };
c620b35d 341 let position = NonZero::new(position).unwrap();
923072b8
FG
342 self.lazy_state = LazyState::Previous(position);
343 f(position)
344 }
345
346 fn read_lazy<T>(&mut self) -> LazyValue<T> {
347 self.read_lazy_offset_then(|pos| LazyValue::from_position(pos))
348 }
349
350 fn read_lazy_array<T>(&mut self, len: usize) -> LazyArray<T> {
351 self.read_lazy_offset_then(|pos| LazyArray::from_position_and_num_elems(pos, len))
352 }
353
781aab86
FG
354 fn read_lazy_table<I, T>(&mut self, width: usize, len: usize) -> LazyTable<I, T> {
355 self.read_lazy_offset_then(|pos| LazyTable::from_position_and_encoded_size(pos, width, len))
9e0c209e 356 }
c295e0f8
XL
357
358 #[inline]
5e7ed085 359 pub fn read_raw_bytes(&mut self, len: usize) -> &[u8] {
c295e0f8
XL
360 self.opaque.read_raw_bytes(len)
361 }
223e47cc
LB
362}
363
923072b8 364impl<'a, 'tcx> TyDecoder for DecodeContext<'a, 'tcx> {
3dfed10e
XL
365 const CLEAR_CROSS_CRATE: bool = true;
366
923072b8
FG
367 type I = TyCtxt<'tcx>;
368
abe05a73 369 #[inline]
923072b8
FG
370 fn interner(&self) -> Self::I {
371 self.tcx()
abe05a73
XL
372 }
373
5099ac24 374 fn cached_ty_for_shorthand<F>(&mut self, shorthand: usize, or_insert_with: F) -> Ty<'tcx>
dfeec247 375 where
5099ac24 376 F: FnOnce(&mut Self) -> Ty<'tcx>,
abe05a73
XL
377 {
378 let tcx = self.tcx();
223e47cc 379
17df50a5 380 let key = ty::CReaderCacheKey { cnum: Some(self.cdata().cnum), pos: shorthand };
1a4d82fc 381
f035d41b 382 if let Some(&ty) = tcx.ty_rcache.borrow().get(&key) {
5099ac24 383 return ty;
abe05a73 384 }
223e47cc 385
5099ac24 386 let ty = or_insert_with(self);
f035d41b 387 tcx.ty_rcache.borrow_mut().insert(key, ty);
5099ac24 388 ty
9e0c209e 389 }
62682a34 390
abe05a73 391 fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
dfeec247
XL
392 where
393 F: FnOnce(&mut Self) -> R,
abe05a73 394 {
49aad941 395 let new_opaque = MemDecoder::new(self.opaque.data(), pos);
abe05a73
XL
396 let old_opaque = mem::replace(&mut self.opaque, new_opaque);
397 let old_state = mem::replace(&mut self.lazy_state, LazyState::NoNode);
398 let r = f(self);
399 self.opaque = old_opaque;
400 self.lazy_state = old_state;
401 r
402 }
403
5099ac24 404 fn decode_alloc_id(&mut self) -> rustc_middle::mir::interpret::AllocId {
3dfed10e
XL
405 if let Some(alloc_decoding_session) = self.alloc_decoding_session {
406 alloc_decoding_session.decode_alloc_id(self)
407 } else {
408 bug!("Attempting to decode interpret::AllocId without CrateMetadata")
409 }
9e0c209e 410 }
223e47cc
LB
411}
412
136023e0 413impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for ExpnIndex {
781aab86 414 #[inline]
5099ac24
FG
415 fn decode(d: &mut DecodeContext<'a, 'tcx>) -> ExpnIndex {
416 ExpnIndex::from_u32(d.read_u32())
136023e0
XL
417 }
418}
419
c0240ec0
FG
420impl<'a, 'tcx> SpanDecoder for DecodeContext<'a, 'tcx> {
421 fn decode_attr_id(&mut self) -> rustc_span::AttrId {
422 let sess = self.sess.expect("can't decode AttrId without Session");
c620b35d 423 sess.psess.attr_id_generator.mk_attr_id()
f2b60f7d 424 }
f2b60f7d 425
c0240ec0
FG
426 fn decode_crate_num(&mut self) -> CrateNum {
427 let cnum = CrateNum::from_u32(self.read_u32());
428 self.map_encoded_cnum_to_current(cnum)
429 }
353b0b11 430
c0240ec0
FG
431 fn decode_def_index(&mut self) -> DefIndex {
432 DefIndex::from_u32(self.read_u32())
433 }
434
435 fn decode_def_id(&mut self) -> DefId {
436 DefId { krate: Decodable::decode(self), index: Decodable::decode(self) }
437 }
438
439 fn decode_syntax_context(&mut self) -> SyntaxContext {
440 let cdata = self.cdata();
441
442 let Some(sess) = self.sess else {
add651ee
FG
443 bug!(
444 "Cannot decode SyntaxContext without Session.\
445 You need to explicitly pass `(crate_metadata_ref, tcx)` to `decode` instead of just `crate_metadata_ref`."
446 );
353b0b11
FG
447 };
448
fe692bf9 449 let cname = cdata.root.name();
c0240ec0 450 rustc_span::hygiene::decode_syntax_context(self, &cdata.hygiene_context, |_, id| {
3dfed10e 451 debug!("SpecializedDecoder<SyntaxContext>: decoding {}", id);
5099ac24 452 cdata
3dfed10e
XL
453 .root
454 .syntax_contexts
5099ac24 455 .get(cdata, id)
9c376795 456 .unwrap_or_else(|| panic!("Missing SyntaxContext {id:?} for crate {cname:?}"))
5099ac24 457 .decode((cdata, sess))
3dfed10e 458 })
1a4d82fc 459 }
1a4d82fc 460
c0240ec0
FG
461 fn decode_expn_id(&mut self) -> ExpnId {
462 let local_cdata = self.cdata();
353b0b11 463
c0240ec0 464 let Some(sess) = self.sess else {
add651ee
FG
465 bug!(
466 "Cannot decode ExpnId without Session. \
467 You need to explicitly pass `(crate_metadata_ref, tcx)` to `decode` instead of just `crate_metadata_ref`."
468 );
353b0b11 469 };
0531ce1d 470
c0240ec0
FG
471 let cnum = CrateNum::decode(self);
472 let index = u32::decode(self);
136023e0
XL
473
474 let expn_id = rustc_span::hygiene::decode_expn_id(cnum, index, |expn_id| {
475 let ExpnId { krate: cnum, local_id: index } = expn_id;
476 // Lookup local `ExpnData`s in our own crate data. Foreign `ExpnData`s
477 // are stored in the owning crate, to avoid duplication.
478 debug_assert_ne!(cnum, LOCAL_CRATE);
479 let crate_data = if cnum == local_cdata.cnum {
480 local_cdata
481 } else {
482 local_cdata.cstore.get_crate_data(cnum)
483 };
484 let expn_data = crate_data
485 .root
486 .expn_data
5099ac24 487 .get(crate_data, index)
136023e0 488 .unwrap()
5099ac24 489 .decode((crate_data, sess));
136023e0
XL
490 let expn_hash = crate_data
491 .root
492 .expn_hashes
5099ac24 493 .get(crate_data, index)
136023e0 494 .unwrap()
5099ac24 495 .decode((crate_data, sess));
136023e0
XL
496 (expn_data, expn_hash)
497 });
5099ac24 498 expn_id
0531ce1d 499 }
0531ce1d 500
c0240ec0
FG
501 fn decode_span(&mut self) -> Span {
502 let start = self.position();
503 let tag = SpanTag(self.peek_byte());
504 let data = if tag.kind() == SpanKind::Indirect {
505 // Skip past the tag we just peek'd.
506 self.read_u8();
c620b35d
FG
507 // indirect tag lengths are safe to access, since they're (0, 8)
508 let bytes_needed = tag.length().unwrap().0 as usize;
509 let mut total = [0u8; usize::BITS as usize / 8];
510 total[..bytes_needed].copy_from_slice(self.read_raw_bytes(bytes_needed));
511 let offset_or_position = usize::from_le_bytes(total);
c0240ec0
FG
512 let position = if tag.is_relative_offset() {
513 start - offset_or_position
514 } else {
515 offset_or_position
516 };
517 self.with_position(position, SpanData::decode)
518 } else {
519 SpanData::decode(self)
add651ee
FG
520 };
521 Span::new(data.lo, data.hi, data.ctxt, data.parent)
522 }
c0240ec0
FG
523
524 fn decode_symbol(&mut self) -> Symbol {
525 let tag = self.read_u8();
526
527 match tag {
528 SYMBOL_STR => {
529 let s = self.read_str();
530 Symbol::intern(s)
531 }
532 SYMBOL_OFFSET => {
533 // read str offset
534 let pos = self.read_usize();
535
536 // move to str offset and read
537 self.opaque.with_position(pos, |d| {
538 let s = d.read_str();
539 Symbol::intern(s)
540 })
541 }
542 SYMBOL_PREINTERNED => {
543 let symbol_index = self.read_u32();
544 Symbol::new_from_decoded(symbol_index)
545 }
546 _ => unreachable!(),
547 }
548 }
add651ee
FG
549}
550
551impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for SpanData {
552 fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> SpanData {
c0240ec0
FG
553 let tag = SpanTag::decode(decoder);
554 let ctxt = tag.context().unwrap_or_else(|| SyntaxContext::decode(decoder));
85aaf69f 555
c0240ec0 556 if tag.kind() == SpanKind::Partial {
add651ee 557 return DUMMY_SP.with_ctxt(ctxt).data();
ff7c6d11
XL
558 }
559
c0240ec0 560 debug_assert!(tag.kind() == SpanKind::Local || tag.kind() == SpanKind::Foreign);
2c00a5a8 561
5099ac24 562 let lo = BytePos::decode(decoder);
c0240ec0 563 let len = tag.length().unwrap_or_else(|| BytePos::decode(decoder));
2c00a5a8 564 let hi = lo + len;
ff7c6d11 565
3c0e092e 566 let Some(sess) = decoder.sess else {
add651ee
FG
567 bug!(
568 "Cannot decode Span without Session. \
569 You need to explicitly pass `(crate_metadata_ref, tcx)` to `decode` instead of just `crate_metadata_ref`."
570 )
9e0c209e 571 };
85aaf69f 572
f2b60f7d
FG
573 // Index of the file in the corresponding crate's list of encoded files.
574 let metadata_index = u32::decode(decoder);
575
ba9703b0
XL
576 // There are two possibilities here:
577 // 1. This is a 'local span', which is located inside a `SourceFile`
578 // that came from this crate. In this case, we use the source map data
579 // encoded in this crate. This branch should be taken nearly all of the time.
580 // 2. This is a 'foreign span', which is located inside a `SourceFile`
581 // that came from a *different* crate (some crate upstream of the one
582 // whose metadata we're looking at). For example, consider this dependency graph:
583 //
584 // A -> B -> C
585 //
586 // Suppose that we're currently compiling crate A, and start deserializing
587 // metadata from crate B. When we deserialize a Span from crate B's metadata,
5e7ed085 588 // there are two possibilities:
ba9703b0
XL
589 //
590 // 1. The span references a file from crate B. This makes it a 'local' span,
591 // which means that we can use crate B's serialized source map information.
592 // 2. The span references a file from crate C. This makes it a 'foreign' span,
593 // which means we need to use Crate *C* (not crate B) to determine the source
594 // map information. We only record source map information for a file in the
595 // crate that 'owns' it, so deserializing a Span may require us to look at
596 // a transitive dependency.
597 //
598 // When we encode a foreign span, we adjust its 'lo' and 'high' values
599 // to be based on the *foreign* crate (e.g. crate C), not the crate
600 // we are writing metadata for (e.g. crate B). This allows us to
601 // treat the 'local' and 'foreign' cases almost identically during deserialization:
f2b60f7d 602 // we can call `imported_source_file` for the proper crate, and binary search
ba9703b0 603 // through the returned slice using our span.
c0240ec0 604 let source_file = if tag.kind() == SpanKind::Local {
f2b60f7d 605 decoder.cdata().imported_source_file(metadata_index, sess)
ba9703b0 606 } else {
f035d41b
XL
607 // When we encode a proc-macro crate, all `Span`s should be encoded
608 // with `TAG_VALID_SPAN_LOCAL`
3dfed10e 609 if decoder.cdata().root.is_proc_macro_crate() {
ba9703b0
XL
610 // Decode `CrateNum` as u32 - using `CrateNum::decode` will ICE
611 // since we don't have `cnum_map` populated.
5099ac24 612 let cnum = u32::decode(decoder);
f035d41b
XL
613 panic!(
614 "Decoding of crate {:?} tried to access proc-macro dep {:?}",
fe692bf9 615 decoder.cdata().root.header.name,
f035d41b
XL
616 cnum
617 );
ba9703b0
XL
618 }
619 // tag is TAG_VALID_SPAN_FOREIGN, checked by `debug_assert` above
5099ac24 620 let cnum = CrateNum::decode(decoder);
ba9703b0
XL
621 debug!(
622 "SpecializedDecoder<Span>::specialized_decode: loading source files from cnum {:?}",
623 cnum
624 );
625
3dfed10e 626 let foreign_data = decoder.cdata().cstore.get_crate_data(cnum);
f2b60f7d 627 foreign_data.imported_source_file(metadata_index, sess)
9e0c209e
SL
628 };
629
f2b60f7d 630 // Make sure our span is well-formed.
ba9703b0 631 debug_assert!(
f2b60f7d
FG
632 lo + source_file.original_start_pos <= source_file.original_end_pos,
633 "Malformed encoded span: lo={:?} source_file.original_start_pos={:?} source_file.original_end_pos={:?}",
ba9703b0
XL
634 lo,
635 source_file.original_start_pos,
636 source_file.original_end_pos
637 );
ff7c6d11 638
f2b60f7d 639 // Make sure we correctly filtered out invalid spans during encoding.
ba9703b0 640 debug_assert!(
f2b60f7d
FG
641 hi + source_file.original_start_pos <= source_file.original_end_pos,
642 "Malformed encoded span: hi={:?} source_file.original_start_pos={:?} source_file.original_end_pos={:?}",
ba9703b0
XL
643 hi,
644 source_file.original_start_pos,
645 source_file.original_end_pos
646 );
ff7c6d11 647
f2b60f7d
FG
648 let lo = lo + source_file.translated_source_file.start_pos;
649 let hi = hi + source_file.translated_source_file.start_pos;
9e0c209e 650
c295e0f8 651 // Do not try to decode parent for foreign spans.
add651ee 652 SpanData { lo, hi, ctxt, parent: None }
e1599b0c
XL
653 }
654}
655
fe692bf9 656impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for &'tcx [(ty::Clause<'tcx>, Span)] {
5099ac24 657 fn decode(d: &mut DecodeContext<'a, 'tcx>) -> Self {
3dfed10e
XL
658 ty::codec::RefDecodable::decode(d)
659 }
660}
661
923072b8 662impl<'a, 'tcx, T> Decodable<DecodeContext<'a, 'tcx>> for LazyValue<T> {
5099ac24 663 fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Self {
923072b8 664 decoder.read_lazy()
2c00a5a8
XL
665 }
666}
667
923072b8 668impl<'a, 'tcx, T> Decodable<DecodeContext<'a, 'tcx>> for LazyArray<T> {
781aab86 669 #[inline]
5099ac24
FG
670 fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Self {
671 let len = decoder.read_usize();
9ffffee4 672 if len == 0 { LazyArray::default() } else { decoder.read_lazy_array(len) }
3dfed10e
XL
673 }
674}
675
923072b8 676impl<'a, 'tcx, I: Idx, T> Decodable<DecodeContext<'a, 'tcx>> for LazyTable<I, T> {
5099ac24 677 fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Self {
781aab86 678 let width = decoder.read_usize();
5099ac24 679 let len = decoder.read_usize();
781aab86 680 decoder.read_lazy_table(width, len)
ff7c6d11
XL
681 }
682}
683
dfeec247 684implement_ty_decoder!(DecodeContext<'a, 'tcx>);
ea8adc8c 685
923072b8 686impl MetadataBlob {
c620b35d
FG
687 pub(crate) fn check_compatibility(
688 &self,
689 cfg_version: &'static str,
690 ) -> Result<(), Option<String>> {
691 if !self.blob().starts_with(METADATA_HEADER) {
692 if self.blob().starts_with(b"rust") {
693 return Err(Some("<unknown rustc version>".to_owned()));
694 }
695 return Err(None);
696 }
85aaf69f 697
c620b35d
FG
698 let found_version =
699 LazyValue::<String>::from_position(NonZero::new(METADATA_HEADER.len() + 8).unwrap())
700 .decode(self);
701 if rustc_version(cfg_version) != found_version {
702 return Err(Some(found_version));
703 }
704
705 Ok(())
476ff2be
SL
706 }
707
c620b35d 708 fn root_pos(&self) -> NonZero<usize> {
fe692bf9 709 let offset = METADATA_HEADER.len();
4b012472
FG
710 let pos_bytes = self.blob()[offset..][..8].try_into().unwrap();
711 let pos = u64::from_le_bytes(pos_bytes);
c620b35d 712 NonZero::new(pos as usize).unwrap()
4b012472 713 }
fe692bf9 714
4b012472
FG
715 pub(crate) fn get_header(&self) -> CrateHeader {
716 let pos = self.root_pos();
717 LazyValue::<CrateHeader>::from_position(pos).decode(self)
fe692bf9
FG
718 }
719
923072b8 720 pub(crate) fn get_root(&self) -> CrateRoot {
4b012472
FG
721 let pos = self.root_pos();
722 LazyValue::<CrateRoot>::from_position(pos).decode(self)
9e0c209e
SL
723 }
724
781aab86
FG
725 pub(crate) fn list_crate_metadata(
726 &self,
727 out: &mut dyn io::Write,
728 ls_kinds: &[String],
729 ) -> io::Result<()> {
9e0c209e 730 let root = self.get_root();
781aab86
FG
731
732 let all_ls_kinds = vec![
733 "root".to_owned(),
734 "lang_items".to_owned(),
735 "features".to_owned(),
736 "items".to_owned(),
737 ];
738 let ls_kinds = if ls_kinds.contains(&"all".to_owned()) { &all_ls_kinds } else { ls_kinds };
739
740 for kind in ls_kinds {
741 match &**kind {
742 "root" => {
743 writeln!(out, "Crate info:")?;
744 writeln!(out, "name {}{}", root.name(), root.extra_filename)?;
745 writeln!(
746 out,
747 "hash {} stable_crate_id {:?}",
748 root.hash(),
749 root.stable_crate_id
750 )?;
751 writeln!(out, "proc_macro {:?}", root.proc_macro_data.is_some())?;
752 writeln!(out, "triple {}", root.header.triple.triple())?;
753 writeln!(out, "edition {}", root.edition)?;
754 writeln!(out, "symbol_mangling_version {:?}", root.symbol_mangling_version)?;
755 writeln!(
756 out,
757 "required_panic_strategy {:?} panic_in_drop_strategy {:?}",
758 root.required_panic_strategy, root.panic_in_drop_strategy
759 )?;
760 writeln!(
761 out,
762 "has_global_allocator {} has_alloc_error_handler {} has_panic_handler {} has_default_lib_allocator {}",
763 root.has_global_allocator,
764 root.has_alloc_error_handler,
765 root.has_panic_handler,
766 root.has_default_lib_allocator
767 )?;
768 writeln!(
769 out,
770 "compiler_builtins {} needs_allocator {} needs_panic_runtime {} no_builtins {} panic_runtime {} profiler_runtime {}",
771 root.compiler_builtins,
772 root.needs_allocator,
773 root.needs_panic_runtime,
774 root.no_builtins,
775 root.panic_runtime,
776 root.profiler_runtime
777 )?;
778
779 writeln!(out, "=External Dependencies=")?;
780 let dylib_dependency_formats =
781 root.dylib_dependency_formats.decode(self).collect::<Vec<_>>();
782 for (i, dep) in root.crate_deps.decode(self).enumerate() {
783 let CrateDep { name, extra_filename, hash, host_hash, kind, is_private } =
784 dep;
785 let number = i + 1;
786
787 writeln!(
788 out,
789 "{number} {name}{extra_filename} hash {hash} host_hash {host_hash:?} kind {kind:?} {privacy}{linkage}",
790 privacy = if is_private { "private" } else { "public" },
791 linkage = if dylib_dependency_formats.is_empty() {
792 String::new()
793 } else {
794 format!(" linkage {:?}", dylib_dependency_formats[i])
795 }
796 )?;
797 }
798 write!(out, "\n")?;
799 }
800
801 "lang_items" => {
802 writeln!(out, "=Lang items=")?;
803 for (id, lang_item) in root.lang_items.decode(self) {
804 writeln!(
805 out,
806 "{} = crate{}",
807 lang_item.name(),
808 DefPath::make(LOCAL_CRATE, id, |parent| root
809 .tables
810 .def_keys
811 .get(self, parent)
812 .unwrap()
813 .decode(self))
814 .to_string_no_crate_verbose()
815 )?;
816 }
817 for lang_item in root.lang_items_missing.decode(self) {
818 writeln!(out, "{} = <missing>", lang_item.name())?;
819 }
820 write!(out, "\n")?;
821 }
822
823 "features" => {
824 writeln!(out, "=Lib features=")?;
825 for (feature, since) in root.lib_features.decode(self) {
826 writeln!(
827 out,
828 "{}{}",
829 feature,
4b012472 830 if let FeatureStability::AcceptedSince(since) = since {
781aab86
FG
831 format!(" since {since}")
832 } else {
833 String::new()
834 }
835 )?;
836 }
837 write!(out, "\n")?;
838 }
839
840 "items" => {
841 writeln!(out, "=Items=")?;
842
843 fn print_item(
844 blob: &MetadataBlob,
845 out: &mut dyn io::Write,
846 item: DefIndex,
847 indent: usize,
848 ) -> io::Result<()> {
849 let root = blob.get_root();
850
4b012472 851 let def_kind = root.tables.def_kind.get(blob, item).unwrap();
781aab86
FG
852 let def_key = root.tables.def_keys.get(blob, item).unwrap().decode(blob);
853 let def_name = if item == CRATE_DEF_INDEX {
854 rustc_span::symbol::kw::Crate
855 } else {
856 def_key
857 .disambiguated_data
858 .data
859 .get_opt_name()
860 .unwrap_or_else(|| Symbol::intern("???"))
861 };
862 let visibility =
863 root.tables.visibility.get(blob, item).unwrap().decode(blob).map_id(
864 |index| {
865 format!(
866 "crate{}",
867 DefPath::make(LOCAL_CRATE, index, |parent| root
868 .tables
869 .def_keys
870 .get(blob, parent)
871 .unwrap()
872 .decode(blob))
873 .to_string_no_crate_verbose()
874 )
875 },
876 );
877 write!(
878 out,
879 "{nil: <indent$}{:?} {:?} {} {{",
880 visibility,
881 def_kind,
882 def_name,
883 nil = "",
884 )?;
885
886 if let Some(children) =
887 root.tables.module_children_non_reexports.get(blob, item)
888 {
889 write!(out, "\n")?;
890 for child in children.decode(blob) {
891 print_item(blob, out, child, indent + 4)?;
892 }
893 writeln!(out, "{nil: <indent$}}}", nil = "")?;
894 } else {
895 writeln!(out, "}}")?;
896 }
897
898 Ok(())
899 }
900
901 print_item(self, out, CRATE_DEF_INDEX, 0)?;
902
903 write!(out, "\n")?;
904 }
905
906 _ => {
907 writeln!(
908 out,
909 "unknown -Zls kind. allowed values are: all, root, lang_items, features, items"
910 )?;
911 }
912 }
1a4d82fc 913 }
781aab86 914
9e0c209e 915 Ok(())
970d7e83 916 }
223e47cc
LB
917}
918
923072b8
FG
919impl CrateRoot {
920 pub(crate) fn is_proc_macro_crate(&self) -> bool {
60c5eb7d
XL
921 self.proc_macro_data.is_some()
922 }
923
923072b8 924 pub(crate) fn name(&self) -> Symbol {
fe692bf9 925 self.header.name
60c5eb7d
XL
926 }
927
923072b8 928 pub(crate) fn hash(&self) -> Svh {
fe692bf9 929 self.header.hash
60c5eb7d
XL
930 }
931
923072b8 932 pub(crate) fn stable_crate_id(&self) -> StableCrateId {
6a06907d
XL
933 self.stable_crate_id
934 }
935
923072b8 936 pub(crate) fn decode_crate_deps<'a>(
60c5eb7d
XL
937 &self,
938 metadata: &'a MetadataBlob,
939 ) -> impl ExactSizeIterator<Item = CrateDep> + Captures<'a> {
940 self.crate_deps.decode(metadata)
941 }
942}
943
74b04a01 944impl<'a, 'tcx> CrateMetadataRef<'a> {
353b0b11
FG
945 fn missing(self, descr: &str, id: DefIndex) -> ! {
946 bug!("missing `{descr}` for {:?}", self.local_def_id(id))
947 }
948
5099ac24 949 fn raw_proc_macro(self, id: DefIndex) -> &'a ProcMacro {
e1599b0c
XL
950 // DefIndex's in root.proc_macro_data have a one-to-one correspondence
951 // with items in 'raw_proc_macros'.
1b1a35ee
XL
952 let pos = self
953 .root
954 .proc_macro_data
955 .as_ref()
956 .unwrap()
957 .macros
958 .decode(self)
959 .position(|i| i == id)
960 .unwrap();
e1599b0c
XL
961 &self.raw_proc_macros.unwrap()[pos]
962 }
963
5e7ed085 964 fn opt_item_name(self, item_index: DefIndex) -> Option<Symbol> {
2b03887a
FG
965 let def_key = self.def_key(item_index);
966 def_key.disambiguated_data.data.get_opt_name().or_else(|| {
967 if def_key.disambiguated_data.data == DefPathData::Ctor {
968 let parent_index = def_key.parent.expect("no parent for a constructor");
969 self.def_key(parent_index).disambiguated_data.data.get_opt_name()
970 } else {
971 None
972 }
973 })
5e7ed085
FG
974 }
975
976 fn item_name(self, item_index: DefIndex) -> Symbol {
977 self.opt_item_name(item_index).expect("no encoded ident for item")
978 }
979
5099ac24 980 fn opt_item_ident(self, item_index: DefIndex, sess: &Session) -> Option<Ident> {
5e7ed085 981 let name = self.opt_item_name(item_index)?;
353b0b11
FG
982 let span = self
983 .root
984 .tables
985 .def_ident_span
986 .get(self, item_index)
987 .unwrap_or_else(|| self.missing("def_ident_span", item_index))
988 .decode((self, sess));
a2a8927a 989 Some(Ident::new(name, span))
223e47cc 990 }
223e47cc 991
5099ac24 992 fn item_ident(self, item_index: DefIndex, sess: &Session) -> Ident {
a2a8927a 993 self.opt_item_ident(item_index, sess).expect("no encoded ident for item")
5869c6ff
XL
994 }
995
04454e1e
FG
996 #[inline]
997 pub(super) fn map_encoded_cnum_to_current(self, cnum: CrateNum) -> CrateNum {
998 if cnum == LOCAL_CRATE { self.cnum } else { self.cnum_map[cnum] }
999 }
1000
5099ac24 1001 fn def_kind(self, item_id: DefIndex) -> DefKind {
4b012472
FG
1002 self.root
1003 .tables
1004 .def_kind
1005 .get(self, item_id)
1006 .unwrap_or_else(|| self.missing("def_kind", item_id))
476ff2be
SL
1007 }
1008
5099ac24 1009 fn get_span(self, index: DefIndex, sess: &Session) -> Span {
1b1a35ee
XL
1010 self.root
1011 .tables
5e7ed085 1012 .def_span
1b1a35ee 1013 .get(self, index)
353b0b11 1014 .unwrap_or_else(|| self.missing("def_span", index))
1b1a35ee 1015 .decode((self, sess))
e1599b0c
XL
1016 }
1017
add651ee 1018 fn load_proc_macro(self, id: DefIndex, tcx: TyCtxt<'tcx>) -> SyntaxExtension {
136023e0 1019 let (name, kind, helper_attrs) = match *self.raw_proc_macro(id) {
e1599b0c
XL
1020 ProcMacro::CustomDerive { trait_name, attributes, client } => {
1021 let helper_attrs =
1022 attributes.iter().cloned().map(Symbol::intern).collect::<Vec<_>>();
1023 (
1024 trait_name,
923072b8 1025 SyntaxExtensionKind::Derive(Box::new(DeriveProcMacro { client })),
e1599b0c
XL
1026 helper_attrs,
1027 )
1028 }
136023e0
XL
1029 ProcMacro::Attr { name, client } => {
1030 (name, SyntaxExtensionKind::Attr(Box::new(AttrProcMacro { client })), Vec::new())
1031 }
1032 ProcMacro::Bang { name, client } => {
1033 (name, SyntaxExtensionKind::Bang(Box::new(BangProcMacro { client })), Vec::new())
1034 }
e1599b0c 1035 };
e1599b0c 1036
add651ee 1037 let sess = tcx.sess;
136023e0 1038 let attrs: Vec<_> = self.get_item_attrs(id, sess).collect();
e1599b0c 1039 SyntaxExtension::new(
3dfed10e 1040 sess,
add651ee 1041 tcx.features(),
e1599b0c 1042 kind,
136023e0 1043 self.get_span(id, sess),
e1599b0c 1044 helper_attrs,
e74abb32 1045 self.root.edition,
e1599b0c 1046 Symbol::intern(name),
fc512014 1047 &attrs,
c0240ec0 1048 false,
e1599b0c 1049 )
7453a54e
SL
1050 }
1051
49aad941
FG
1052 fn get_explicit_item_bounds(
1053 self,
1054 index: DefIndex,
1055 tcx: TyCtxt<'tcx>,
fe692bf9 1056 ) -> ty::EarlyBinder<&'tcx [(ty::Clause<'tcx>, Span)]> {
49aad941
FG
1057 let lazy = self.root.tables.explicit_item_bounds.get(self, index);
1058 let output = if lazy.is_default() {
1059 &mut []
1060 } else {
1061 tcx.arena.alloc_from_iter(lazy.decode((self, tcx)))
1062 };
fe692bf9 1063 ty::EarlyBinder::bind(&*output)
49aad941
FG
1064 }
1065
353b0b11
FG
1066 fn get_variant(
1067 self,
1068 kind: DefKind,
1069 index: DefIndex,
1070 parent_did: DefId,
1071 ) -> (VariantIdx, ty::VariantDef) {
e74abb32 1072 let adt_kind = match kind {
f2b60f7d
FG
1073 DefKind::Variant => ty::AdtKind::Enum,
1074 DefKind::Struct => ty::AdtKind::Struct,
1075 DefKind::Union => ty::AdtKind::Union,
e74abb32
XL
1076 _ => bug!(),
1077 };
1078
f2b60f7d
FG
1079 let data = self.root.tables.variant_data.get(self, index).unwrap().decode(self);
1080
dfeec247
XL
1081 let variant_did =
1082 if adt_kind == ty::AdtKind::Enum { Some(self.local_def_id(index)) } else { None };
487cf647 1083 let ctor = data.ctor.map(|(kind, index)| (kind, self.local_def_id(index)));
0bf4aa26 1084
353b0b11
FG
1085 (
1086 data.idx,
1087 ty::VariantDef::new(
1088 self.item_name(index),
1089 variant_did,
1090 ctor,
1091 data.discr,
49aad941
FG
1092 self.get_associated_item_or_field_def_ids(index)
1093 .map(|did| ty::FieldDef {
1094 did,
1095 name: self.item_name(did.index),
1096 vis: self.get_visibility(did.index),
353b0b11
FG
1097 })
1098 .collect(),
1099 adt_kind,
1100 parent_did,
1101 false,
1102 data.is_non_exhaustive,
c620b35d
FG
1103 // FIXME: unnamed fields in crate metadata is unimplemented yet.
1104 false,
353b0b11 1105 ),
b7449926 1106 )
c30ab7b3
SL
1107 }
1108
5e7ed085 1109 fn get_adt_def(self, item_id: DefIndex, tcx: TyCtxt<'tcx>) -> ty::AdtDef<'tcx> {
f2b60f7d 1110 let kind = self.def_kind(item_id);
9e0c209e 1111 let did = self.local_def_id(item_id);
94b46f34 1112
5e7ed085 1113 let adt_kind = match kind {
f2b60f7d
FG
1114 DefKind::Enum => ty::AdtKind::Enum,
1115 DefKind::Struct => ty::AdtKind::Struct,
1116 DefKind::Union => ty::AdtKind::Union,
8bb4bdeb
XL
1117 _ => bug!("get_adt_def called on a non-ADT {:?}", did),
1118 };
5e7ed085 1119 let repr = self.root.tables.repr_options.get(self, item_id).unwrap().decode(self);
94b46f34 1120
353b0b11 1121 let mut variants: Vec<_> = if let ty::AdtKind::Enum = adt_kind {
dfeec247 1122 self.root
ba9703b0 1123 .tables
49aad941 1124 .module_children_non_reexports
dfeec247 1125 .get(self, item_id)
9ffffee4 1126 .expect("variants are not encoded for an enum")
c30ab7b3 1127 .decode(self)
2b03887a
FG
1128 .filter_map(|index| {
1129 let kind = self.def_kind(index);
1130 match kind {
1131 DefKind::Ctor(..) => None,
353b0b11 1132 _ => Some(self.get_variant(kind, index, did)),
2b03887a
FG
1133 }
1134 })
c30ab7b3
SL
1135 .collect()
1136 } else {
353b0b11 1137 std::iter::once(self.get_variant(kind, item_id, did)).collect()
9e0c209e 1138 };
9cc50fc6 1139
353b0b11 1140 variants.sort_by_key(|(idx, _)| *idx);
9cc50fc6 1141
353b0b11
FG
1142 tcx.mk_adt_def(
1143 did,
1144 adt_kind,
1145 variants.into_iter().map(|(_, variant)| variant).collect(),
1146 repr,
c620b35d 1147 false,
353b0b11 1148 )
9e0c209e 1149 }
1a4d82fc 1150
353b0b11 1151 fn get_visibility(self, id: DefIndex) -> Visibility<DefId> {
f2b60f7d
FG
1152 self.root
1153 .tables
1154 .visibility
1155 .get(self, id)
353b0b11 1156 .unwrap_or_else(|| self.missing("visibility", id))
f2b60f7d
FG
1157 .decode(self)
1158 .map_id(|index| self.local_def_id(index))
9e0c209e 1159 }
1a4d82fc 1160
5099ac24 1161 fn get_trait_item_def_id(self, id: DefIndex) -> Option<DefId> {
923072b8 1162 self.root.tables.trait_item_def_id.get(self, id).map(|d| d.decode_from_cdata(self))
5099ac24
FG
1163 }
1164
5099ac24 1165 fn get_expn_that_defined(self, id: DefIndex, sess: &Session) -> ExpnId {
353b0b11
FG
1166 self.root
1167 .tables
1168 .expn_that_defined
1169 .get(self, id)
1170 .unwrap_or_else(|| self.missing("expn_that_defined", id))
1171 .decode((self, sess))
29967ef6
XL
1172 }
1173
49aad941 1174 fn get_debugger_visualizers(self) -> Vec<DebuggerVisualizerFile> {
04454e1e
FG
1175 self.root.debugger_visualizers.decode(self).collect::<Vec<_>>()
1176 }
1177
b7449926 1178 /// Iterates over all the stability attributes in the given crate.
4b012472
FG
1179 fn get_lib_features(self) -> LibFeatures {
1180 LibFeatures {
1181 stability: self
1182 .root
1183 .lib_features
1184 .decode(self)
1185 .map(|(sym, stab)| (sym, (stab, DUMMY_SP)))
1186 .collect(),
1187 }
9e0c209e 1188 }
223e47cc 1189
064997fb
FG
1190 /// Iterates over the stability implications in the given crate (when a `#[unstable]` attribute
1191 /// has an `implied_by` meta item, then the mapping from the implied feature to the actual
1192 /// feature is a stability implication).
1193 fn get_stability_implications(self, tcx: TyCtxt<'tcx>) -> &'tcx [(Symbol, Symbol)] {
1194 tcx.arena.alloc_from_iter(self.root.stability_implications.decode(self))
1195 }
1196
b7449926 1197 /// Iterates over the language items in the given crate.
487cf647 1198 fn get_lang_items(self, tcx: TyCtxt<'tcx>) -> &'tcx [(DefId, LangItem)] {
5e7ed085
FG
1199 tcx.arena.alloc_from_iter(
1200 self.root
1201 .lang_items
1202 .decode(self)
1203 .map(move |(def_index, index)| (self.local_def_id(def_index), index)),
1204 )
b7449926
XL
1205 }
1206
fe692bf9
FG
1207 fn get_stripped_cfg_items(self, cnum: CrateNum, tcx: TyCtxt<'tcx>) -> &'tcx [StrippedCfgItem] {
1208 let item_names = self
1209 .root
1210 .stripped_cfg_items
1211 .decode((self, tcx))
1212 .map(|item| item.map_mod_id(|index| DefId { krate: cnum, index }));
1213 tcx.arena.alloc_from_iter(item_names)
1214 }
1215
e1599b0c 1216 /// Iterates over the diagnostic items in the given crate.
5099ac24 1217 fn get_diagnostic_items(self) -> DiagnosticItems {
4b012472 1218 let mut id_to_name = DefIdMap::default();
5099ac24
FG
1219 let name_to_id = self
1220 .root
1221 .diagnostic_items
1222 .decode(self)
1223 .map(|(name, def_index)| {
1224 let id = self.local_def_id(def_index);
1225 id_to_name.insert(id, name);
1226 (name, id)
1227 })
1228 .collect();
1229 DiagnosticItems { id_to_name, name_to_id }
e1599b0c
XL
1230 }
1231
487cf647
FG
1232 fn get_mod_child(self, id: DefIndex, sess: &Session) -> ModChild {
1233 let ident = self.item_ident(id, sess);
353b0b11 1234 let res = Res::Def(self.def_kind(id), self.local_def_id(id));
487cf647 1235 let vis = self.get_visibility(id);
487cf647 1236
49aad941 1237 ModChild { ident, res, vis, reexport_chain: Default::default() }
487cf647
FG
1238 }
1239
5099ac24
FG
1240 /// Iterates over all named children of the given module,
1241 /// including both proper items and reexports.
1242 /// Module here is understood in name resolution sense - it can be a `mod` item,
1243 /// or a crate root, or an enum, or a trait.
487cf647 1244 fn get_module_children(
5099ac24
FG
1245 self,
1246 id: DefIndex,
487cf647
FG
1247 sess: &'a Session,
1248 ) -> impl Iterator<Item = ModChild> + 'a {
ed00b5ec 1249 iter::from_coroutine(move || {
487cf647
FG
1250 if let Some(data) = &self.root.proc_macro_data {
1251 // If we are loading as a proc macro, we want to return
1252 // the view of this crate as a proc macro crate.
1253 if id == CRATE_DEF_INDEX {
1254 for child_index in data.macros.decode(self) {
1255 yield self.get_mod_child(child_index, sess);
f2b60f7d 1256 }
487cf647
FG
1257 }
1258 } else {
1259 // Iterate over all children.
49aad941
FG
1260 let non_reexports = self.root.tables.module_children_non_reexports.get(self, id);
1261 for child_index in non_reexports.unwrap().decode(self) {
1262 yield self.get_mod_child(child_index, sess);
487cf647 1263 }
04454e1e 1264
353b0b11
FG
1265 let reexports = self.root.tables.module_children_reexports.get(self, id);
1266 if !reexports.is_default() {
487cf647
FG
1267 for reexport in reexports.decode((self, sess)) {
1268 yield reexport;
04454e1e 1269 }
d9579d0f
AL
1270 }
1271 }
487cf647 1272 })
9e0c209e 1273 }
1a4d82fc 1274
5099ac24 1275 fn is_ctfe_mir_available(self, id: DefIndex) -> bool {
5869c6ff
XL
1276 self.root.tables.mir_for_ctfe.get(self, id).is_some()
1277 }
1278
5099ac24 1279 fn is_item_mir_available(self, id: DefIndex) -> bool {
5e7ed085 1280 self.root.tables.optimized_mir.get(self, id).is_some()
9e0c209e 1281 }
1a4d82fc 1282
ed00b5ec 1283 fn cross_crate_inlinable(self, id: DefIndex) -> bool {
c0240ec0 1284 self.root.tables.cross_crate_inlinable.get(self, id)
ed00b5ec
FG
1285 }
1286
f2b60f7d
FG
1287 fn get_fn_has_self_parameter(self, id: DefIndex, sess: &'a Session) -> bool {
1288 self.root
1289 .tables
1290 .fn_arg_names
1291 .get(self, id)
9ffffee4 1292 .expect("argument names not encoded for a function")
f2b60f7d
FG
1293 .decode((self, sess))
1294 .nth(0)
49aad941 1295 .is_some_and(|ident| ident.name == kw::SelfLower)
a2a8927a
XL
1296 }
1297
49aad941 1298 fn get_associated_item_or_field_def_ids(
04454e1e
FG
1299 self,
1300 id: DefIndex,
04454e1e
FG
1301 ) -> impl Iterator<Item = DefId> + 'a {
1302 self.root
1303 .tables
49aad941 1304 .associated_item_or_field_def_ids
04454e1e 1305 .get(self, id)
49aad941
FG
1306 .unwrap_or_else(|| self.missing("associated_item_or_field_def_ids", id))
1307 .decode(self)
04454e1e 1308 .map(move |child_index| self.local_def_id(child_index))
5099ac24
FG
1309 }
1310
f2b60f7d 1311 fn get_associated_item(self, id: DefIndex, sess: &'a Session) -> ty::AssocItem {
353b0b11
FG
1312 let name = if self.root.tables.opt_rpitit_info.get(self, id).is_some() {
1313 kw::Empty
1314 } else {
1315 self.item_name(id)
1316 };
9ffffee4
FG
1317 let (kind, has_self) = match self.def_kind(id) {
1318 DefKind::AssocConst => (ty::AssocKind::Const, false),
1319 DefKind::AssocFn => (ty::AssocKind::Fn, self.get_fn_has_self_parameter(id, sess)),
1320 DefKind::AssocTy => (ty::AssocKind::Type, false),
f2b60f7d 1321 _ => bug!("cannot get associated-item of `{:?}`", self.def_key(id)),
8bb4bdeb 1322 };
f2b60f7d 1323 let container = self.root.tables.assoc_container.get(self, id).unwrap();
353b0b11
FG
1324 let opt_rpitit_info =
1325 self.root.tables.opt_rpitit_info.get(self, id).map(|d| d.decode(self));
8bb4bdeb 1326
dc9dc135 1327 ty::AssocItem {
5e7ed085 1328 name,
3b2f2976 1329 kind,
8bb4bdeb 1330 def_id: self.local_def_id(id),
5099ac24 1331 trait_item_def_id: self.get_trait_item_def_id(id),
064997fb 1332 container,
ba9703b0 1333 fn_has_self_parameter: has_self,
353b0b11 1334 opt_rpitit_info,
8bb4bdeb 1335 }
9e0c209e 1336 }
223e47cc 1337
487cf647 1338 fn get_ctor(self, node_id: DefIndex) -> Option<(CtorKind, DefId)> {
f2b60f7d
FG
1339 match self.def_kind(node_id) {
1340 DefKind::Struct | DefKind::Variant => {
1341 let vdata = self.root.tables.variant_data.get(self, node_id).unwrap().decode(self);
487cf647 1342 vdata.ctor.map(|(kind, index)| (kind, self.local_def_id(index)))
9e0c209e 1343 }
c30ab7b3 1344 _ => None,
9e0c209e 1345 }
223e47cc
LB
1346 }
1347
fc512014 1348 fn get_item_attrs(
5099ac24 1349 self,
a2a8927a 1350 id: DefIndex,
fc512014
XL
1351 sess: &'a Session,
1352 ) -> impl Iterator<Item = ast::Attribute> + 'a {
ba9703b0
XL
1353 self.root
1354 .tables
1355 .attributes
a2a8927a
XL
1356 .get(self, id)
1357 .unwrap_or_else(|| {
1358 // Structure and variant constructors don't have any attributes encoded for them,
1359 // but we assume that someone passing a constructor ID actually wants to look at
1360 // the attributes on the corresponding struct or variant.
1361 let def_key = self.def_key(id);
1362 assert_eq!(def_key.disambiguated_data.data, DefPathData::Ctor);
1363 let parent_id = def_key.parent.expect("no parent for a constructor");
1364 self.root
1365 .tables
1366 .attributes
1367 .get(self, parent_id)
1368 .expect("no encoded attributes for a structure or variant")
1369 })
ba9703b0 1370 .decode((self, sess))
9e0c209e 1371 }
223e47cc 1372
60c5eb7d 1373 fn get_inherent_implementations_for_type(
5099ac24 1374 self,
dc9dc135
XL
1375 tcx: TyCtxt<'tcx>,
1376 id: DefIndex,
1377 ) -> &'tcx [DefId] {
e74abb32 1378 tcx.arena.alloc_from_iter(
dfeec247 1379 self.root
ba9703b0 1380 .tables
dfeec247
XL
1381 .inherent_impls
1382 .get(self, id)
e74abb32 1383 .decode(self)
dfeec247 1384 .map(|index| self.local_def_id(index)),
e74abb32 1385 )
9e0c209e 1386 }
223e47cc 1387
5099ac24
FG
1388 /// Decodes all traits in the crate (for rustdoc and rustc diagnostics).
1389 fn get_traits(self) -> impl Iterator<Item = DefId> + 'a {
1390 self.root.traits.decode(self).map(move |index| self.local_def_id(index))
1391 }
1392
1393 /// Decodes all trait impls in the crate (for rustdoc).
9ffffee4
FG
1394 fn get_trait_impls(self) -> impl Iterator<Item = DefId> + 'a {
1395 self.cdata.trait_impls.values().flat_map(move |impls| {
1396 impls.decode(self).map(move |(impl_index, _)| self.local_def_id(impl_index))
a2a8927a
XL
1397 })
1398 }
1399
5e7ed085
FG
1400 fn get_incoherent_impls(self, tcx: TyCtxt<'tcx>, simp: SimplifiedType) -> &'tcx [DefId] {
1401 if let Some(impls) = self.cdata.incoherent_impls.get(&simp) {
1402 tcx.arena.alloc_from_iter(impls.decode(self).map(|idx| self.local_def_id(idx)))
1403 } else {
1404 &[]
1405 }
1406 }
1407
a2a8927a 1408 fn get_implementations_of_trait(
5099ac24 1409 self,
dc9dc135 1410 tcx: TyCtxt<'tcx>,
a2a8927a
XL
1411 trait_def_id: DefId,
1412 ) -> &'tcx [(DefId, Option<SimplifiedType>)] {
5099ac24 1413 if self.trait_impls.is_empty() {
dfeec247 1414 return &[];
b7449926
XL
1415 }
1416
a2a8927a
XL
1417 // Do a reverse lookup beforehand to avoid touching the crate_num
1418 // hash map in the loop below.
1419 let key = match self.reverse_translate_def_id(trait_def_id) {
1420 Some(def_id) => (def_id.krate.as_u32(), def_id.index),
1421 None => return &[],
1422 };
223e47cc 1423
a2a8927a
XL
1424 if let Some(impls) = self.trait_impls.get(&key) {
1425 tcx.arena.alloc_from_iter(
3dfed10e
XL
1426 impls
1427 .decode(self)
a2a8927a
XL
1428 .map(|(idx, simplified_self_ty)| (self.local_def_id(idx), simplified_self_ty)),
1429 )
1430 } else {
1431 &[]
9e0c209e
SL
1432 }
1433 }
223e47cc 1434
5099ac24
FG
1435 fn get_native_libraries(self, sess: &'a Session) -> impl Iterator<Item = NativeLib> + 'a {
1436 self.root.native_libraries.decode((self, sess))
223e47cc
LB
1437 }
1438
5099ac24 1439 fn get_proc_macro_quoted_span(self, index: usize, sess: &Session) -> Span {
17df50a5
XL
1440 self.root
1441 .tables
1442 .proc_macro_quoted_spans
1443 .get(self, index)
9c376795 1444 .unwrap_or_else(|| panic!("Missing proc macro quoted span: {index:?}"))
17df50a5
XL
1445 .decode((self, sess))
1446 }
1447
5099ac24
FG
1448 fn get_foreign_modules(self, sess: &'a Session) -> impl Iterator<Item = ForeignModule> + '_ {
1449 self.root.foreign_modules.decode((self, sess))
0531ce1d
XL
1450 }
1451
60c5eb7d 1452 fn get_dylib_dependency_formats(
5099ac24 1453 self,
dc9dc135
XL
1454 tcx: TyCtxt<'tcx>,
1455 ) -> &'tcx [(CrateNum, LinkagePreference)] {
dfeec247
XL
1456 tcx.arena.alloc_from_iter(
1457 self.root.dylib_dependency_formats.decode(self).enumerate().flat_map(|(i, link)| {
c30ab7b3 1458 let cnum = CrateNum::new(i + 1);
94b46f34 1459 link.map(|link| (self.cnum_map[cnum], link))
dfeec247
XL
1460 }),
1461 )
223e47cc 1462 }
223e47cc 1463
487cf647 1464 fn get_missing_lang_items(self, tcx: TyCtxt<'tcx>) -> &'tcx [LangItem] {
5099ac24 1465 tcx.arena.alloc_from_iter(self.root.lang_items_missing.decode(self))
d9579d0f
AL
1466 }
1467
60c5eb7d 1468 fn exported_symbols(
5099ac24 1469 self,
dc9dc135 1470 tcx: TyCtxt<'tcx>,
04454e1e 1471 ) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportInfo)] {
5099ac24 1472 tcx.arena.alloc_from_iter(self.root.exported_symbols.decode((self, tcx)))
83c7162d
XL
1473 }
1474
5e7ed085 1475 fn get_macro(self, id: DefIndex, sess: &Session) -> ast::MacroDef {
f2b60f7d
FG
1476 match self.def_kind(id) {
1477 DefKind::Macro(_) => {
9ffffee4 1478 let macro_rules = self.root.tables.is_macro_rules.get(self, id);
f2b60f7d
FG
1479 let body =
1480 self.root.tables.macro_definition.get(self, id).unwrap().decode((self, sess));
1481 ast::MacroDef { macro_rules, body: ast::ptr::P(body) }
5e7ed085 1482 }
476ff2be
SL
1483 _ => bug!(),
1484 }
9e0c209e 1485 }
9cc50fc6 1486
cc61c64b 1487 #[inline]
5099ac24 1488 fn def_key(self, index: DefIndex) -> DefKey {
fc512014
XL
1489 *self
1490 .def_key_cache
1491 .lock()
1492 .entry(index)
1493 .or_insert_with(|| self.root.tables.def_keys.get(self, index).unwrap().decode(self))
1494 }
1495
32a655c1 1496 // Returns the path leading to the thing with this `id`.
5099ac24 1497 fn def_path(self, id: DefIndex) -> DefPath {
b7449926 1498 debug!("def_path(cnum={:?}, id={:?})", self.cnum, id);
e1599b0c 1499 DefPath::make(self.cnum, id, |parent| self.def_key(parent))
92a42be0 1500 }
92a42be0 1501
3dfed10e 1502 #[inline]
5099ac24 1503 fn def_path_hash(self, index: DefIndex) -> DefPathHash {
c0240ec0
FG
1504 // This is a hack to workaround the fact that we can't easily encode/decode a Hash64
1505 // into the FixedSizeEncoding, as Hash64 lacks a Default impl. A future refactor to
1506 // relax the Default restriction will likely fix this.
1507 let fingerprint = Fingerprint::new(
1508 self.root.stable_crate_id.as_u64(),
1509 self.root.tables.def_path_hashes.get(self, index),
1510 );
1511 DefPathHash::new(self.root.stable_crate_id, fingerprint.split().1)
3dfed10e
XL
1512 }
1513
c295e0f8 1514 #[inline]
5099ac24 1515 fn def_path_hash_to_def_index(self, hash: DefPathHash) -> DefIndex {
c295e0f8
XL
1516 self.def_path_hash_map.def_path_hash_to_def_index(&hash)
1517 }
1518
5099ac24 1519 fn expn_hash_to_expn_id(self, sess: &Session, index_guess: u32, hash: ExpnHash) -> ExpnId {
136023e0
XL
1520 debug_assert_eq!(ExpnId::from_hash(hash), None);
1521 let index_guess = ExpnIndex::from_u32(index_guess);
1522 let old_hash = self.root.expn_hashes.get(self, index_guess).map(|lazy| lazy.decode(self));
1523
1524 let index = if old_hash == Some(hash) {
1525 // Fast path: the expn and its index is unchanged from the
1526 // previous compilation session. There is no need to decode anything
1527 // else.
1528 index_guess
1529 } else {
1530 // Slow path: We need to find out the new `DefIndex` of the provided
1531 // `DefPathHash`, if its still exists. This requires decoding every `DefPathHash`
1532 // stored in this crate.
1533 let map = self.cdata.expn_hash_map.get_or_init(|| {
1534 let end_id = self.root.expn_hashes.size() as u32;
1535 let mut map =
1536 UnhashMap::with_capacity_and_hasher(end_id as usize, Default::default());
1537 for i in 0..end_id {
1538 let i = ExpnIndex::from_u32(i);
1539 if let Some(hash) = self.root.expn_hashes.get(self, i) {
1540 map.insert(hash.decode(self), i);
136023e0
XL
1541 }
1542 }
1543 map
1544 });
1545 map[&hash]
1546 };
1547
c295e0f8 1548 let data = self.root.expn_data.get(self, index).unwrap().decode((self, sess));
136023e0
XL
1549 rustc_span::hygiene::register_expn_id(self.cnum, index, data, hash)
1550 }
1551
b7449926 1552 /// Imports the source_map from an external crate into the source_map of the crate
9e0c209e
SL
1553 /// currently being compiled (the "local crate").
1554 ///
1555 /// The import algorithm works analogous to how AST items are inlined from an
1556 /// external crate's metadata:
b7449926
XL
1557 /// For every SourceFile in the external source_map an 'inline' copy is created in the
1558 /// local source_map. The correspondence relation between external and local
1559 /// SourceFiles is recorded in the `ImportedSourceFile` objects returned from this
9e0c209e
SL
1560 /// function. When an item from an external crate is later inlined into this
1561 /// crate, this correspondence information is used to translate the span
1562 /// information of the inlined item so that it refers the correct positions in
b7449926 1563 /// the local source_map (see `<decoder::DecodeContext as SpecializedDecoder<Span>>`).
9e0c209e 1564 ///
b7449926
XL
1565 /// The import algorithm in the function below will reuse SourceFiles already
1566 /// existing in the local source_map. For example, even if the SourceFile of some
9e0c209e 1567 /// source file of libstd gets imported many times, there will only ever be
b7449926 1568 /// one SourceFile object for the corresponding file in the local source_map.
9e0c209e 1569 ///
b7449926 1570 /// Note that imported SourceFiles do not actually contain the source code of the
9e0c209e
SL
1571 /// file they represent, just information about length, line breaks, and
1572 /// multibyte characters. This information is enough to generate valid debuginfo
1573 /// for items inlined from other crates.
b7449926
XL
1574 ///
1575 /// Proc macro crates don't currently export spans, so this function does not have
1576 /// to work for them.
f2b60f7d 1577 fn imported_source_file(self, source_file_index: u32, sess: &Session) -> ImportedSourceFile {
064997fb
FG
1578 fn filter<'a>(sess: &Session, path: Option<&'a Path>) -> Option<&'a Path> {
1579 path.filter(|_| {
ba9703b0 1580 // Only spend time on further checks if we have what to translate *to*.
cdc7bbd5 1581 sess.opts.real_rust_source_base_dir.is_some()
064997fb
FG
1582 // Some tests need the translation to be always skipped.
1583 && sess.opts.unstable_opts.translate_remapped_path_to_local_path
ba9703b0
XL
1584 })
1585 .filter(|virtual_dir| {
1586 // Don't translate away `/rustc/$hash` if we're still remapping to it,
1587 // since that means we're still building `std`/`rustc` that need it,
1588 // and we don't want the real path to leak into codegen/debuginfo.
1589 !sess.opts.remap_path_prefix.iter().any(|(_from, to)| to == virtual_dir)
064997fb
FG
1590 })
1591 }
1592
1593 // Translate the virtual `/rustc/$hash` prefix back to a real directory
1594 // that should hold actual sources, where possible.
1595 //
1596 // NOTE: if you update this, you might need to also update bootstrap's code for generating
1597 // the `rust-src` component in `Src::run` in `src/bootstrap/dist.rs`.
1598 let virtual_rust_source_base_dir = [
1599 filter(sess, option_env!("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR").map(Path::new)),
1600 filter(sess, sess.opts.unstable_opts.simulate_remapped_rust_src_base.as_deref()),
1601 ];
1602
ba9703b0
XL
1603 let try_to_translate_virtual_to_real = |name: &mut rustc_span::FileName| {
1604 debug!(
1605 "try_to_translate_virtual_to_real(name={:?}): \
1606 virtual_rust_source_base_dir={:?}, real_rust_source_base_dir={:?}",
cdc7bbd5 1607 name, virtual_rust_source_base_dir, sess.opts.real_rust_source_base_dir,
ba9703b0
XL
1608 );
1609
064997fb 1610 for virtual_dir in virtual_rust_source_base_dir.iter().flatten() {
cdc7bbd5 1611 if let Some(real_dir) = &sess.opts.real_rust_source_base_dir {
ba9703b0 1612 if let rustc_span::FileName::Real(old_name) = name {
17df50a5
XL
1613 if let rustc_span::RealFileName::Remapped { local_path: _, virtual_name } =
1614 old_name
1615 {
1616 if let Ok(rest) = virtual_name.strip_prefix(virtual_dir) {
1617 let virtual_name = virtual_name.clone();
3dfed10e
XL
1618
1619 // The std library crates are in
1620 // `$sysroot/lib/rustlib/src/rust/library`, whereas other crates
1621 // may be in `$sysroot/lib/rustlib/src/rust/` directly. So we
1622 // detect crates from the std libs and handle them specially.
1623 const STD_LIBS: &[&str] = &[
1624 "core",
1625 "alloc",
1626 "std",
1627 "test",
1628 "term",
1629 "unwind",
1630 "proc_macro",
1631 "panic_abort",
1632 "panic_unwind",
1633 "profiler_builtins",
1634 "rtstartup",
1635 "rustc-std-workspace-core",
1636 "rustc-std-workspace-alloc",
1637 "rustc-std-workspace-std",
1638 "backtrace",
1639 ];
1640 let is_std_lib = STD_LIBS.iter().any(|l| rest.starts_with(l));
1641
1642 let new_path = if is_std_lib {
1643 real_dir.join("library").join(rest)
1644 } else {
1645 real_dir.join(rest)
1646 };
1647
ba9703b0
XL
1648 debug!(
1649 "try_to_translate_virtual_to_real: `{}` -> `{}`",
1650 virtual_name.display(),
1651 new_path.display(),
1652 );
17df50a5
XL
1653 let new_name = rustc_span::RealFileName::Remapped {
1654 local_path: Some(new_path),
ba9703b0
XL
1655 virtual_name,
1656 };
1657 *old_name = new_name;
1658 }
1659 }
1660 }
1661 }
1662 }
1663 };
1664
f2b60f7d
FG
1665 let mut import_info = self.cdata.source_map_import_info.lock();
1666 for _ in import_info.len()..=(source_file_index as usize) {
1667 import_info.push(None);
1668 }
1669 import_info[source_file_index as usize]
1670 .get_or_insert_with(|| {
1671 let source_file_to_import = self
1672 .root
1673 .source_map
1674 .get(self, source_file_index)
1675 .expect("missing source file")
1676 .decode(self);
1677
1678 // We can't reuse an existing SourceFile, so allocate a new one
1679 // containing the information we need.
781aab86 1680 let original_end_pos = source_file_to_import.end_position();
f2b60f7d
FG
1681 let rustc_span::SourceFile {
1682 mut name,
1683 src_hash,
781aab86
FG
1684 start_pos: original_start_pos,
1685 source_len,
f2b60f7d
FG
1686 lines,
1687 multibyte_chars,
1688 non_narrow_chars,
1689 normalized_pos,
c0240ec0 1690 stable_id,
f2b60f7d
FG
1691 ..
1692 } = source_file_to_import;
1693
49aad941
FG
1694 // If this file is under $sysroot/lib/rustlib/src/
1695 // and the user wish to simulate remapping with -Z simulate-remapped-rust-src-base,
f2b60f7d
FG
1696 // then we change `name` to a similar state as if the rust was bootstrapped
1697 // with `remap-debuginfo = true`.
1698 // This is useful for testing so that tests about the effects of
1699 // `try_to_translate_virtual_to_real` don't have to worry about how the
1700 // compiler is bootstrapped.
1701 if let Some(virtual_dir) = &sess.opts.unstable_opts.simulate_remapped_rust_src_base
ed00b5ec
FG
1702 && let Some(real_dir) = &sess.opts.real_rust_source_base_dir
1703 && let rustc_span::FileName::Real(ref mut old_name) = name
1704 {
49aad941 1705 let relative_path = match old_name {
ed00b5ec
FG
1706 rustc_span::RealFileName::LocalPath(local) => {
1707 local.strip_prefix(real_dir).ok()
1708 }
49aad941 1709 rustc_span::RealFileName::Remapped { virtual_name, .. } => {
ed00b5ec
FG
1710 option_env!("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR")
1711 .and_then(|virtual_dir| virtual_name.strip_prefix(virtual_dir).ok())
49aad941
FG
1712 }
1713 };
1714 debug!(?relative_path, ?virtual_dir, "simulate_remapped_rust_src_base");
1715 for subdir in ["library", "compiler"] {
ed00b5ec
FG
1716 if let Some(rest) = relative_path.and_then(|p| p.strip_prefix(subdir).ok())
1717 {
49aad941
FG
1718 *old_name = rustc_span::RealFileName::Remapped {
1719 local_path: None, // FIXME: maybe we should preserve this?
1720 virtual_name: virtual_dir.join(subdir).join(rest),
1721 };
1722 break;
17df50a5
XL
1723 }
1724 }
f2b60f7d 1725 }
17df50a5 1726
f2b60f7d
FG
1727 // If this file's path has been remapped to `/rustc/$hash`,
1728 // we might be able to reverse that (also see comments above,
1729 // on `try_to_translate_virtual_to_real`).
1730 try_to_translate_virtual_to_real(&mut name);
1731
f2b60f7d
FG
1732 let local_version = sess.source_map().new_imported_source_file(
1733 name,
1734 src_hash,
c0240ec0 1735 stable_id,
781aab86 1736 source_len.to_u32(),
f2b60f7d
FG
1737 self.cnum,
1738 lines,
1739 multibyte_chars,
1740 non_narrow_chars,
1741 normalized_pos,
f2b60f7d
FG
1742 source_file_index,
1743 );
1744 debug!(
1745 "CrateMetaData::imported_source_files alloc \
781aab86
FG
1746 source_file {:?} original (start_pos {:?} source_len {:?}) \
1747 translated (start_pos {:?} source_len {:?})",
f2b60f7d 1748 local_version.name,
781aab86
FG
1749 original_start_pos,
1750 source_len,
f2b60f7d 1751 local_version.start_pos,
781aab86 1752 local_version.source_len
f2b60f7d 1753 );
e74abb32 1754
f2b60f7d 1755 ImportedSourceFile {
781aab86
FG
1756 original_start_pos,
1757 original_end_pos,
f2b60f7d
FG
1758 translated_source_file: local_version,
1759 }
1760 })
1761 .clone()
e74abb32 1762 }
04454e1e 1763
9ffffee4
FG
1764 fn get_attr_flags(self, index: DefIndex) -> AttrFlags {
1765 self.root.tables.attr_flags.get(self, index)
04454e1e 1766 }
923072b8 1767
c620b35d
FG
1768 fn get_intrinsic(self, index: DefIndex) -> Option<ty::IntrinsicDef> {
1769 self.root.tables.intrinsic.get(self, index).map(|d| d.decode(self))
9ffffee4
FG
1770 }
1771
1772 fn get_doc_link_resolutions(self, index: DefIndex) -> DocLinkResMap {
1773 self.root
1774 .tables
1775 .doc_link_resolutions
1776 .get(self, index)
1777 .expect("no resolutions for a doc link")
1778 .decode(self)
1779 }
1780
1781 fn get_doc_link_traits_in_scope(self, index: DefIndex) -> impl Iterator<Item = DefId> + 'a {
1782 self.root
1783 .tables
1784 .doc_link_traits_in_scope
1785 .get(self, index)
1786 .expect("no traits in scope for a doc link")
1787 .decode(self)
923072b8 1788 }
74b04a01 1789}
0531ce1d 1790
74b04a01 1791impl CrateMetadata {
923072b8 1792 pub(crate) fn new(
74b04a01 1793 sess: &Session,
04454e1e 1794 cstore: &CStore,
74b04a01 1795 blob: MetadataBlob,
923072b8 1796 root: CrateRoot,
74b04a01
XL
1797 raw_proc_macros: Option<&'static [ProcMacro]>,
1798 cnum: CrateNum,
1799 cnum_map: CrateNumMap,
3dfed10e 1800 dep_kind: CrateDepKind,
74b04a01
XL
1801 source: CrateSource,
1802 private_dep: bool,
1803 host_hash: Option<Svh>,
1804 ) -> CrateMetadata {
74b04a01
XL
1805 let trait_impls = root
1806 .impls
1807 .decode((&blob, sess))
1808 .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls))
1809 .collect();
1810 let alloc_decoding_state =
1811 AllocDecodingState::new(root.interpret_alloc_index.decode(&blob).collect());
353b0b11 1812 let dependencies = cnum_map.iter().copied().collect();
c295e0f8
XL
1813
1814 // Pre-decode the DefPathHash->DefIndex table. This is a cheap operation
1815 // that does not copy any data. It just does some data verification.
1816 let def_path_hash_map = root.def_path_hash_map.decode(&blob);
1817
04454e1e 1818 let mut cdata = CrateMetadata {
74b04a01
XL
1819 blob,
1820 root,
74b04a01 1821 trait_impls,
04454e1e 1822 incoherent_impls: Default::default(),
74b04a01 1823 raw_proc_macros,
f2b60f7d 1824 source_map_import_info: Lock::new(Vec::new()),
c295e0f8 1825 def_path_hash_map,
136023e0 1826 expn_hash_map: Default::default(),
74b04a01 1827 alloc_decoding_state,
74b04a01
XL
1828 cnum,
1829 cnum_map,
1830 dependencies,
c0240ec0 1831 dep_kind,
5099ac24 1832 source: Lrc::new(source),
c0240ec0 1833 private_dep,
74b04a01 1834 host_hash,
c620b35d 1835 used: false,
c0240ec0 1836 extern_crate: None,
3dfed10e
XL
1837 hygiene_context: Default::default(),
1838 def_key_cache: Default::default(),
04454e1e
FG
1839 };
1840
1841 // Need `CrateMetadataRef` to decode `DefId`s in simplified types.
1842 cdata.incoherent_impls = cdata
1843 .root
1844 .incoherent_impls
1845 .decode(CrateMetadataRef { cdata: &cdata, cstore })
1846 .map(|incoherent_impls| (incoherent_impls.self_ty, incoherent_impls.impls))
1847 .collect();
1848
1849 cdata
b039eaaf 1850 }
60c5eb7d 1851
353b0b11 1852 pub(crate) fn dependencies(&self) -> impl Iterator<Item = CrateNum> + '_ {
c0240ec0 1853 self.dependencies.iter().copied()
60c5eb7d
XL
1854 }
1855
c0240ec0 1856 pub(crate) fn add_dependency(&mut self, cnum: CrateNum) {
353b0b11 1857 self.dependencies.push(cnum);
60c5eb7d
XL
1858 }
1859
c0240ec0
FG
1860 pub(crate) fn update_extern_crate(&mut self, new_extern_crate: ExternCrate) -> bool {
1861 let update =
1862 Some(new_extern_crate.rank()) > self.extern_crate.as_ref().map(ExternCrate::rank);
60c5eb7d 1863 if update {
c0240ec0 1864 self.extern_crate = Some(new_extern_crate);
60c5eb7d
XL
1865 }
1866 update
1867 }
1868
923072b8 1869 pub(crate) fn source(&self) -> &CrateSource {
5099ac24 1870 &*self.source
60c5eb7d
XL
1871 }
1872
923072b8 1873 pub(crate) fn dep_kind(&self) -> CrateDepKind {
c0240ec0 1874 self.dep_kind
60c5eb7d
XL
1875 }
1876
c0240ec0
FG
1877 pub(crate) fn set_dep_kind(&mut self, dep_kind: CrateDepKind) {
1878 self.dep_kind = dep_kind;
60c5eb7d
XL
1879 }
1880
c0240ec0
FG
1881 pub(crate) fn update_and_private_dep(&mut self, private_dep: bool) {
1882 self.private_dep &= private_dep;
fe692bf9
FG
1883 }
1884
c620b35d
FG
1885 pub(crate) fn used(&self) -> bool {
1886 self.used
1887 }
1888
064997fb
FG
1889 pub(crate) fn required_panic_strategy(&self) -> Option<PanicStrategy> {
1890 self.root.required_panic_strategy
60c5eb7d
XL
1891 }
1892
923072b8 1893 pub(crate) fn needs_panic_runtime(&self) -> bool {
60c5eb7d
XL
1894 self.root.needs_panic_runtime
1895 }
1896
923072b8 1897 pub(crate) fn is_panic_runtime(&self) -> bool {
60c5eb7d
XL
1898 self.root.panic_runtime
1899 }
1900
923072b8 1901 pub(crate) fn is_profiler_runtime(&self) -> bool {
60c5eb7d
XL
1902 self.root.profiler_runtime
1903 }
1904
923072b8 1905 pub(crate) fn needs_allocator(&self) -> bool {
60c5eb7d
XL
1906 self.root.needs_allocator
1907 }
1908
923072b8 1909 pub(crate) fn has_global_allocator(&self) -> bool {
60c5eb7d
XL
1910 self.root.has_global_allocator
1911 }
1912
487cf647
FG
1913 pub(crate) fn has_alloc_error_handler(&self) -> bool {
1914 self.root.has_alloc_error_handler
1915 }
1916
923072b8 1917 pub(crate) fn has_default_lib_allocator(&self) -> bool {
60c5eb7d
XL
1918 self.root.has_default_lib_allocator
1919 }
1920
923072b8 1921 pub(crate) fn is_proc_macro_crate(&self) -> bool {
60c5eb7d
XL
1922 self.root.is_proc_macro_crate()
1923 }
1924
923072b8 1925 pub(crate) fn name(&self) -> Symbol {
fe692bf9 1926 self.root.header.name
60c5eb7d
XL
1927 }
1928
923072b8 1929 pub(crate) fn hash(&self) -> Svh {
fe692bf9 1930 self.root.header.hash
60c5eb7d 1931 }
74b04a01 1932
3dfed10e
XL
1933 fn num_def_ids(&self) -> usize {
1934 self.root.tables.def_keys.size()
1935 }
1936
74b04a01
XL
1937 fn local_def_id(&self, index: DefIndex) -> DefId {
1938 DefId { krate: self.cnum, index }
1939 }
1940
1941 // Translate a DefId from the current compilation environment to a DefId
1942 // for an external crate.
1943 fn reverse_translate_def_id(&self, did: DefId) -> Option<DefId> {
1944 for (local, &global) in self.cnum_map.iter_enumerated() {
1945 if global == did.krate {
1946 return Some(DefId { krate: local, index: did.index });
1947 }
1948 }
1949
1950 None
1951 }
a7813a04 1952}