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