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