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