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