1use std::iter::TrustedLen;
4use std::ops::{Deref, DerefMut};
5use std::path::{Path, PathBuf};
6use std::sync::{Arc, OnceLock};
7use std::{io, mem};
8
9pub(super) use cstore_impl::provide;
10use rustc_ast as ast;
11use rustc_data_structures::fingerprint::Fingerprint;
12use rustc_data_structures::fx::FxIndexMap;
13use rustc_data_structures::owned_slice::OwnedSlice;
14use rustc_data_structures::sync::Lock;
15use rustc_data_structures::unhash::UnhashMap;
16use rustc_expand::base::{SyntaxExtension, SyntaxExtensionKind};
17use rustc_expand::proc_macro::{AttrProcMacro, BangProcMacro, DeriveProcMacro};
18use rustc_hir::Safety;
19use rustc_hir::def::Res;
20use rustc_hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE};
21use rustc_hir::definitions::{DefPath, DefPathData};
22use rustc_hir::diagnostic_items::DiagnosticItems;
23use rustc_index::Idx;
24use rustc_middle::middle::lib_features::LibFeatures;
25use rustc_middle::mir::interpret::{AllocDecodingSession, AllocDecodingState};
26use rustc_middle::ty::Visibility;
27use rustc_middle::ty::codec::TyDecoder;
28use rustc_middle::{bug, implement_ty_decoder};
29use rustc_proc_macro::bridge::client::Client as ProcMacroClient;
30use rustc_serialize::opaque::MemDecoder;
31use rustc_serialize::{Decodable, Decoder};
32use rustc_session::config::TargetModifier;
33use rustc_session::config::mitigation_coverage::DeniedPartialMitigation;
34use rustc_session::cstore::{CrateSource, ExternCrate};
35use rustc_span::def_id::ModId;
36use rustc_span::hygiene::HygieneDecodeContext;
37use rustc_span::{
38 BlobDecoder, BytePos, ByteSymbol, DUMMY_SP, Pos, RemapPathScopeComponents, SpanData,
39 SpanDecoder, Symbol, SyntaxContext, kw,
40};
41use tracing::debug;
42
43use crate::creader::CStore;
44use crate::eii::EiiMapEncodedKeyValue;
45use crate::rmeta::table::IsDefault;
46use crate::rmeta::*;
47
48mod cstore_impl;
49
50pub(crate) struct MetadataBlob(OwnedSlice);
54
55impl std::ops::Deref for MetadataBlob {
56 type Target = [u8];
57
58 #[inline]
59 fn deref(&self) -> &[u8] {
60 &self.0[..]
61 }
62}
63
64impl MetadataBlob {
65 pub(crate) fn new(slice: OwnedSlice) -> Result<Self, ()> {
67 if MemDecoder::new(&slice, 0).is_ok() { Ok(Self(slice)) } else { Err(()) }
68 }
69
70 pub(crate) fn bytes(&self) -> &OwnedSlice {
73 &self.0
74 }
75}
76
77pub(crate) type CrateNumMap = IndexVec<CrateNum, CrateNum>;
82
83pub(crate) type TargetModifiers = Vec<TargetModifier>;
86
87pub(crate) type DeniedPartialMitigations = Vec<DeniedPartialMitigation>;
91
92pub(crate) struct CrateMetadata {
93 blob: MetadataBlob,
95
96 root: CrateRoot,
99 trait_impls: FxIndexMap<(u32, DefIndex), LazyArray<(DefIndex, Option<SimplifiedType>)>>,
103 incoherent_impls: FxIndexMap<SimplifiedType, LazyArray<DefIndex>>,
108 raw_proc_macros: Option<&'static [ProcMacroClient]>,
110 source_map_import_info: Lock<Vec<Option<ImportedSourceFile>>>,
112 def_path_hash_map: DefPathHashMapRef<'static>,
114 expn_hash_map: OnceLock<UnhashMap<ExpnHash, ExpnIndex>>,
116 alloc_decoding_state: AllocDecodingState,
118 def_key_cache: Lock<FxHashMap<DefIndex, DefKey>>,
120
121 cnum: CrateNum,
124 cnum_map: CrateNumMap,
127 dep_kind: CrateDepKind,
129 source: Arc<CrateSource>,
131 private_dep: bool,
135 host_hash: Option<Svh>,
137 used: bool,
139
140 hygiene_context: HygieneDecodeContext,
146
147 extern_crate: Option<ExternCrate>,
151}
152
153#[derive(#[automatically_derived]
impl ::core::clone::Clone for ImportedSourceFile {
#[inline]
fn clone(&self) -> ImportedSourceFile {
ImportedSourceFile {
original_start_pos: ::core::clone::Clone::clone(&self.original_start_pos),
original_end_pos: ::core::clone::Clone::clone(&self.original_end_pos),
translated_source_file: ::core::clone::Clone::clone(&self.translated_source_file),
}
}
}Clone)]
156struct ImportedSourceFile {
157 original_start_pos: rustc_span::BytePos,
159 original_end_pos: rustc_span::BytePos,
161 translated_source_file: Arc<rustc_span::SourceFile>,
163}
164
165pub(super) struct BlobDecodeContext<'a> {
169 opaque: MemDecoder<'a>,
170 blob: &'a MetadataBlob,
171 lazy_state: LazyState,
172}
173
174pub(super) trait LazyDecoder: BlobDecoder {
180 fn set_lazy_state(&mut self, state: LazyState);
181 fn get_lazy_state(&self) -> LazyState;
182
183 fn read_lazy<T>(&mut self) -> LazyValue<T> {
184 self.read_lazy_offset_then(|pos| LazyValue::from_position(pos))
185 }
186
187 fn read_lazy_array<T>(&mut self, len: usize) -> LazyArray<T> {
188 self.read_lazy_offset_then(|pos| LazyArray::from_position_and_num_elems(pos, len))
189 }
190
191 fn read_lazy_table<I, T>(&mut self, width: usize, len: usize) -> LazyTable<I, T> {
192 self.read_lazy_offset_then(|pos| LazyTable::from_position_and_encoded_size(pos, width, len))
193 }
194
195 #[inline]
196 fn read_lazy_offset_then<T>(&mut self, f: impl Fn(NonZero<usize>) -> T) -> T {
197 let distance = self.read_usize();
198 let position = match self.get_lazy_state() {
199 LazyState::NoNode => ::rustc_middle::util::bug::bug_fmt(format_args!("read_lazy_with_meta: outside of a metadata node"))bug!("read_lazy_with_meta: outside of a metadata node"),
200 LazyState::NodeStart(start) => {
201 let start = start.get();
202 if !(distance <= start) {
::core::panicking::panic("assertion failed: distance <= start")
};assert!(distance <= start);
203 start - distance
204 }
205 LazyState::Previous(last_pos) => last_pos.get() + distance,
206 };
207 let position = NonZero::new(position).unwrap();
208 self.set_lazy_state(LazyState::Previous(position));
209 f(position)
210 }
211}
212
213impl<'a> LazyDecoder for BlobDecodeContext<'a> {
214 fn set_lazy_state(&mut self, state: LazyState) {
215 self.lazy_state = state;
216 }
217
218 fn get_lazy_state(&self) -> LazyState {
219 self.lazy_state
220 }
221}
222
223pub(super) struct MetadataDecodeContext<'a, 'tcx> {
228 blob_decoder: BlobDecodeContext<'a>,
229 cdata: &'a CrateMetadata,
230 tcx: TyCtxt<'tcx>,
231
232 alloc_decoding_session: AllocDecodingSession<'a>,
234}
235
236impl<'a, 'tcx> LazyDecoder for MetadataDecodeContext<'a, 'tcx> {
237 fn set_lazy_state(&mut self, state: LazyState) {
238 self.lazy_state = state;
239 }
240
241 fn get_lazy_state(&self) -> LazyState {
242 self.lazy_state
243 }
244}
245
246impl<'a, 'tcx> DerefMut for MetadataDecodeContext<'a, 'tcx> {
247 fn deref_mut(&mut self) -> &mut Self::Target {
248 &mut self.blob_decoder
249 }
250}
251
252impl<'a, 'tcx> Deref for MetadataDecodeContext<'a, 'tcx> {
253 type Target = BlobDecodeContext<'a>;
254
255 fn deref(&self) -> &Self::Target {
256 &self.blob_decoder
257 }
258}
259
260pub(super) trait MetaBlob<'a>: Copy {
261 fn blob(&self) -> &'a MetadataBlob;
262}
263
264pub(super) trait MetaDecoder: Copy {
265 type Context: BlobDecoder + LazyDecoder;
266
267 fn decoder(self, pos: usize) -> Self::Context;
268}
269
270impl<'a> MetaBlob<'a> for &'a MetadataBlob {
271 fn blob(&self) -> &'a MetadataBlob {
272 self
273 }
274}
275
276impl<'a> MetaDecoder for &'a MetadataBlob {
277 type Context = BlobDecodeContext<'a>;
278
279 fn decoder(self, pos: usize) -> Self::Context {
280 BlobDecodeContext {
281 opaque: MemDecoder::new(self, pos).unwrap(),
289 lazy_state: LazyState::NoNode,
290 blob: self.blob(),
291 }
292 }
293}
294
295impl<'a> MetaBlob<'a> for &'a CrateMetadata {
296 fn blob(&self) -> &'a MetadataBlob {
297 &self.blob
298 }
299}
300
301impl<'a, 'tcx> MetaDecoder for (&'a CrateMetadata, TyCtxt<'tcx>) {
302 type Context = MetadataDecodeContext<'a, 'tcx>;
303
304 fn decoder(self, pos: usize) -> MetadataDecodeContext<'a, 'tcx> {
305 MetadataDecodeContext {
306 blob_decoder: self.0.blob().decoder(pos),
307 cdata: self.0,
308 tcx: self.1,
309 alloc_decoding_session: self.0.alloc_decoding_state.new_decoding_session(),
310 }
311 }
312}
313
314impl<T: ParameterizedOverTcx> LazyValue<T> {
315 #[inline]
316 fn decode<'tcx, M: MetaDecoder>(self, metadata: M) -> T::Value<'tcx>
317 where
318 T::Value<'tcx>: Decodable<M::Context>,
319 {
320 let mut dcx = metadata.decoder(self.position.get());
321 dcx.set_lazy_state(LazyState::NodeStart(self.position));
322 T::Value::decode(&mut dcx)
323 }
324}
325
326struct DecodeIterator<T, D> {
327 elem_counter: std::ops::Range<usize>,
328 dcx: D,
329 _phantom: PhantomData<fn() -> T>,
330}
331
332impl<D: Decoder, T: Decodable<D>> Iterator for DecodeIterator<T, D> {
333 type Item = T;
334
335 #[inline(always)]
336 fn next(&mut self) -> Option<Self::Item> {
337 self.elem_counter.next().map(|_| T::decode(&mut self.dcx))
338 }
339
340 #[inline(always)]
341 fn size_hint(&self) -> (usize, Option<usize>) {
342 self.elem_counter.size_hint()
343 }
344}
345
346impl<D: Decoder, T: Decodable<D>> ExactSizeIterator for DecodeIterator<T, D> {
347 fn len(&self) -> usize {
348 self.elem_counter.len()
349 }
350}
351
352unsafe impl<D: Decoder, T: Decodable<D>> TrustedLen for DecodeIterator<T, D> {}
353
354impl<T: ParameterizedOverTcx> LazyArray<T> {
355 #[inline]
356 fn decode<'tcx, M: MetaDecoder>(self, metadata: M) -> DecodeIterator<T::Value<'tcx>, M::Context>
357 where
358 T::Value<'tcx>: Decodable<M::Context>,
359 {
360 let mut dcx = metadata.decoder(self.position.get());
361 dcx.set_lazy_state(LazyState::NodeStart(self.position));
362 DecodeIterator { elem_counter: (0..self.num_elems), dcx, _phantom: PhantomData }
363 }
364}
365
366impl<'a, 'tcx> MetadataDecodeContext<'a, 'tcx> {
367 #[inline]
368 fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum {
369 self.cdata.map_encoded_cnum_to_current(cnum)
370 }
371}
372
373impl<'a> BlobDecodeContext<'a> {
374 #[inline]
375 pub(crate) fn blob(&self) -> &'a MetadataBlob {
376 self.blob
377 }
378
379 fn decode_symbol_or_byte_symbol<S>(
380 &mut self,
381 new_from_index: impl Fn(u32) -> S,
382 read_and_intern_str_or_byte_str_this: impl Fn(&mut Self) -> S,
383 read_and_intern_str_or_byte_str_opaque: impl Fn(&mut MemDecoder<'a>) -> S,
384 ) -> S {
385 let tag = self.read_u8();
386
387 match tag {
388 SYMBOL_STR => read_and_intern_str_or_byte_str_this(self),
389 SYMBOL_OFFSET => {
390 let pos = self.read_usize();
392
393 self.opaque.with_position(pos, |d| read_and_intern_str_or_byte_str_opaque(d))
395 }
396 SYMBOL_PREDEFINED => new_from_index(self.read_u32()),
397 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
398 }
399 }
400}
401
402impl<'a, 'tcx> TyDecoder<'tcx> for MetadataDecodeContext<'a, 'tcx> {
403 const CLEAR_CROSS_CRATE: bool = true;
404
405 #[inline]
406 fn interner(&self) -> TyCtxt<'tcx> {
407 self.tcx
408 }
409
410 fn cached_ty_for_shorthand<F>(&mut self, shorthand: usize, or_insert_with: F) -> Ty<'tcx>
411 where
412 F: FnOnce(&mut Self) -> Ty<'tcx>,
413 {
414 let tcx = self.tcx;
415
416 let key = ty::CReaderCacheKey { cnum: Some(self.cdata.cnum), pos: shorthand };
417
418 if let Some(&ty) = tcx.ty_rcache.borrow().get(&key) {
419 return ty;
420 }
421
422 let ty = or_insert_with(self);
423 tcx.ty_rcache.borrow_mut().insert(key, ty);
424 ty
425 }
426
427 fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
428 where
429 F: FnOnce(&mut Self) -> R,
430 {
431 let new_opaque = self.blob_decoder.opaque.split_at(pos);
432 let old_opaque = mem::replace(&mut self.blob_decoder.opaque, new_opaque);
433 let old_state = mem::replace(&mut self.blob_decoder.lazy_state, LazyState::NoNode);
434 let r = f(self);
435 self.blob_decoder.opaque = old_opaque;
436 self.blob_decoder.lazy_state = old_state;
437 r
438 }
439
440 fn decode_alloc_id(&mut self) -> rustc_middle::mir::interpret::AllocId {
441 let ads = self.alloc_decoding_session;
442 ads.decode_alloc_id(self)
443 }
444}
445
446impl<'a, 'tcx> Decodable<MetadataDecodeContext<'a, 'tcx>> for ExpnIndex {
447 #[inline]
448 fn decode(d: &mut MetadataDecodeContext<'a, 'tcx>) -> ExpnIndex {
449 ExpnIndex::from_u32(d.read_u32())
450 }
451}
452
453impl<'a, 'tcx> SpanDecoder for MetadataDecodeContext<'a, 'tcx> {
454 fn decode_attr_id(&mut self) -> rustc_span::AttrId {
455 self.tcx.sess.psess.attr_id_generator.mk_attr_id()
456 }
457
458 fn decode_crate_num(&mut self) -> CrateNum {
459 let cnum = CrateNum::from_u32(self.read_u32());
460 self.map_encoded_cnum_to_current(cnum)
461 }
462
463 fn decode_def_id(&mut self) -> DefId {
464 DefId { krate: Decodable::decode(self), index: Decodable::decode(self) }
465 }
466
467 fn decode_syntax_context(&mut self) -> SyntaxContext {
468 let cdata = self.cdata;
469 let tcx = self.tcx;
470
471 let cname = cdata.root.name();
472 rustc_span::hygiene::decode_syntax_context(self, &cdata.hygiene_context, |_, id| {
473 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/rmeta/decoder.rs:473",
"rustc_metadata::rmeta::decoder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/rmeta/decoder.rs"),
::tracing_core::__macro_support::Option::Some(473u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::decoder"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("SpecializedDecoder<SyntaxContext>: decoding {0}",
id) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("SpecializedDecoder<SyntaxContext>: decoding {}", id);
474 cdata
475 .root
476 .syntax_contexts
477 .get(cdata, id)
478 .unwrap_or_else(|| {
::core::panicking::panic_fmt(format_args!("Missing SyntaxContext {0:?} for crate {1:?}",
id, cname));
}panic!("Missing SyntaxContext {id:?} for crate {cname:?}"))
479 .decode((cdata, tcx))
480 })
481 }
482
483 fn decode_expn_id(&mut self) -> ExpnId {
484 let tcx = self.tcx;
485 let cnum = CrateNum::decode(self);
486 let index = u32::decode(self);
487
488 let expn_id = rustc_span::hygiene::decode_expn_id(cnum, index, |expn_id| {
489 let ExpnId { krate: cnum, local_id: index } = expn_id;
490 if true {
{
match (&cnum, &LOCAL_CRATE) {
(left_val, right_val) => {
if *left_val == *right_val {
let kind = ::core::panicking::AssertKind::Ne;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
};debug_assert_ne!(cnum, LOCAL_CRATE);
493 let cstore;
494 let cdata = if cnum == self.cdata.cnum {
495 self.cdata
496 } else {
497 cstore = CStore::from_tcx(tcx);
498 cstore.get_crate_data(cnum)
499 };
500 let expn_data = cdata.root.expn_data.get(cdata, index).unwrap().decode((cdata, tcx));
501 let expn_hash = cdata.root.expn_hashes.get(cdata, index).unwrap().decode((cdata, tcx));
502 (expn_data, expn_hash)
503 });
504 expn_id
505 }
506
507 fn decode_span(&mut self) -> Span {
508 let start = self.position();
509 let tag = SpanTag(self.peek_byte());
510 let data = if tag.kind() == SpanKind::Indirect {
511 self.read_u8();
513 let bytes_needed = tag.length().unwrap().0 as usize;
515 let mut total = [0u8; usize::BITS as usize / 8];
516 total[..bytes_needed].copy_from_slice(self.read_raw_bytes(bytes_needed));
517 let offset_or_position = usize::from_le_bytes(total);
518 let position = if tag.is_relative_offset() {
519 start - offset_or_position
520 } else {
521 offset_or_position
522 };
523 self.with_position(position, SpanData::decode)
524 } else {
525 SpanData::decode(self)
526 };
527 data.span()
528 }
529}
530
531impl<'a, 'tcx> BlobDecoder for MetadataDecodeContext<'a, 'tcx> {
532 fn decode_def_index(&mut self) -> DefIndex {
533 self.blob_decoder.decode_def_index()
534 }
535 fn decode_symbol(&mut self) -> Symbol {
536 self.blob_decoder.decode_symbol()
537 }
538
539 fn decode_byte_symbol(&mut self) -> ByteSymbol {
540 self.blob_decoder.decode_byte_symbol()
541 }
542}
543
544impl<'a> BlobDecoder for BlobDecodeContext<'a> {
545 fn decode_def_index(&mut self) -> DefIndex {
546 DefIndex::from_u32(self.read_u32())
547 }
548 fn decode_symbol(&mut self) -> Symbol {
549 self.decode_symbol_or_byte_symbol(
550 Symbol::new,
551 |this| Symbol::intern(this.read_str()),
552 |opaque| Symbol::intern(opaque.read_str()),
553 )
554 }
555
556 fn decode_byte_symbol(&mut self) -> ByteSymbol {
557 self.decode_symbol_or_byte_symbol(
558 ByteSymbol::new,
559 |this| ByteSymbol::intern(this.read_byte_str()),
560 |opaque| ByteSymbol::intern(opaque.read_byte_str()),
561 )
562 }
563}
564
565impl<'a, 'tcx> Decodable<MetadataDecodeContext<'a, 'tcx>> for SpanData {
566 fn decode(decoder: &mut MetadataDecodeContext<'a, 'tcx>) -> SpanData {
567 let tag = SpanTag::decode(decoder);
568 let ctxt = tag.context().unwrap_or_else(|| SyntaxContext::decode(decoder));
569
570 if tag.kind() == SpanKind::Partial {
571 return DUMMY_SP.with_ctxt(ctxt).data();
572 }
573
574 if true {
if !(tag.kind() == SpanKind::Local || tag.kind() == SpanKind::Foreign) {
::core::panicking::panic("assertion failed: tag.kind() == SpanKind::Local || tag.kind() == SpanKind::Foreign")
};
};debug_assert!(tag.kind() == SpanKind::Local || tag.kind() == SpanKind::Foreign);
575
576 let lo = BytePos::decode(decoder);
577 let len = tag.length().unwrap_or_else(|| BytePos::decode(decoder));
578 let hi = lo + len;
579
580 let tcx = decoder.tcx;
581
582 let metadata_index = u32::decode(decoder);
584
585 let source_file = if tag.kind() == SpanKind::Local {
614 decoder.cdata.imported_source_file(tcx, metadata_index)
615 } else {
616 if decoder.cdata.root.is_proc_macro_crate() {
619 let cnum = u32::decode(decoder);
622 {
::core::panicking::panic_fmt(format_args!("Decoding of crate {0:?} tried to access proc-macro dep {1:?}",
decoder.cdata.root.header.name, cnum));
};panic!(
623 "Decoding of crate {:?} tried to access proc-macro dep {:?}",
624 decoder.cdata.root.header.name, cnum
625 );
626 }
627 let cnum = CrateNum::decode(decoder);
629 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/rmeta/decoder.rs:629",
"rustc_metadata::rmeta::decoder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/rmeta/decoder.rs"),
::tracing_core::__macro_support::Option::Some(629u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::decoder"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("SpecializedDecoder<Span>::specialized_decode: loading source files from cnum {0:?}",
cnum) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
630 "SpecializedDecoder<Span>::specialized_decode: loading source files from cnum {:?}",
631 cnum
632 );
633
634 let cstore = CStore::from_tcx(tcx);
635 let foreign_cdata = cstore.get_crate_data(cnum);
636 foreign_cdata.imported_source_file(tcx, metadata_index)
637 };
638
639 if true {
if !(lo + source_file.original_start_pos <= source_file.original_end_pos)
{
{
::core::panicking::panic_fmt(format_args!("Malformed encoded span: lo={0:?} source_file.original_start_pos={1:?} source_file.original_end_pos={2:?}",
lo, source_file.original_start_pos,
source_file.original_end_pos));
}
};
};debug_assert!(
641 lo + source_file.original_start_pos <= source_file.original_end_pos,
642 "Malformed encoded span: lo={:?} source_file.original_start_pos={:?} source_file.original_end_pos={:?}",
643 lo,
644 source_file.original_start_pos,
645 source_file.original_end_pos
646 );
647
648 if true {
if !(hi + source_file.original_start_pos <= source_file.original_end_pos)
{
{
::core::panicking::panic_fmt(format_args!("Malformed encoded span: hi={0:?} source_file.original_start_pos={1:?} source_file.original_end_pos={2:?}",
hi, source_file.original_start_pos,
source_file.original_end_pos));
}
};
};debug_assert!(
650 hi + source_file.original_start_pos <= source_file.original_end_pos,
651 "Malformed encoded span: hi={:?} source_file.original_start_pos={:?} source_file.original_end_pos={:?}",
652 hi,
653 source_file.original_start_pos,
654 source_file.original_end_pos
655 );
656
657 let lo = lo + source_file.translated_source_file.start_pos;
658 let hi = hi + source_file.translated_source_file.start_pos;
659
660 SpanData { lo, hi, ctxt, parent: None }
662 }
663}
664
665impl<'a, 'tcx> Decodable<MetadataDecodeContext<'a, 'tcx>> for &'tcx [(ty::Clause<'tcx>, Span)] {
666 fn decode(d: &mut MetadataDecodeContext<'a, 'tcx>) -> Self {
667 ty::codec::RefDecodable::decode(d)
668 }
669}
670
671impl<D: LazyDecoder, T> Decodable<D> for LazyValue<T> {
672 fn decode(decoder: &mut D) -> Self {
673 decoder.read_lazy()
674 }
675}
676
677impl<D: LazyDecoder, T> Decodable<D> for LazyArray<T> {
678 #[inline]
679 fn decode(decoder: &mut D) -> Self {
680 let len = decoder.read_usize();
681 if len == 0 { LazyArray::default() } else { decoder.read_lazy_array(len) }
682 }
683}
684
685impl<I: Idx, D: LazyDecoder, T> Decodable<D> for LazyTable<I, T> {
686 fn decode(decoder: &mut D) -> Self {
687 let width = decoder.read_usize();
688 let len = decoder.read_usize();
689 decoder.read_lazy_table(width, len)
690 }
691}
692
693mod meta {
694 use super::*;
695 mod __ty_decoder_impl {
use rustc_serialize::Decoder;
use super::MetadataDecodeContext;
impl<'a, 'tcx> Decoder for MetadataDecodeContext<'a, 'tcx> {
#[inline]
fn read_usize(&mut self) -> usize { self.opaque.read_usize() }
#[inline]
fn read_u128(&mut self) -> u128 { self.opaque.read_u128() }
#[inline]
fn read_u64(&mut self) -> u64 { self.opaque.read_u64() }
#[inline]
fn read_u32(&mut self) -> u32 { self.opaque.read_u32() }
#[inline]
fn read_u16(&mut self) -> u16 { self.opaque.read_u16() }
#[inline]
fn read_u8(&mut self) -> u8 { self.opaque.read_u8() }
#[inline]
fn read_isize(&mut self) -> isize { self.opaque.read_isize() }
#[inline]
fn read_i128(&mut self) -> i128 { self.opaque.read_i128() }
#[inline]
fn read_i64(&mut self) -> i64 { self.opaque.read_i64() }
#[inline]
fn read_i32(&mut self) -> i32 { self.opaque.read_i32() }
#[inline]
fn read_i16(&mut self) -> i16 { self.opaque.read_i16() }
#[inline]
fn read_raw_bytes(&mut self, len: usize) -> &[u8] {
self.opaque.read_raw_bytes(len)
}
#[inline]
fn peek_byte(&self) -> u8 { self.opaque.peek_byte() }
#[inline]
fn position(&self) -> usize { self.opaque.position() }
}
}implement_ty_decoder!(MetadataDecodeContext<'a, 'tcx>);
696}
697mod blob {
698 use super::*;
699 mod __ty_decoder_impl {
use rustc_serialize::Decoder;
use super::BlobDecodeContext;
impl<'a> Decoder for BlobDecodeContext<'a> {
#[inline]
fn read_usize(&mut self) -> usize { self.opaque.read_usize() }
#[inline]
fn read_u128(&mut self) -> u128 { self.opaque.read_u128() }
#[inline]
fn read_u64(&mut self) -> u64 { self.opaque.read_u64() }
#[inline]
fn read_u32(&mut self) -> u32 { self.opaque.read_u32() }
#[inline]
fn read_u16(&mut self) -> u16 { self.opaque.read_u16() }
#[inline]
fn read_u8(&mut self) -> u8 { self.opaque.read_u8() }
#[inline]
fn read_isize(&mut self) -> isize { self.opaque.read_isize() }
#[inline]
fn read_i128(&mut self) -> i128 { self.opaque.read_i128() }
#[inline]
fn read_i64(&mut self) -> i64 { self.opaque.read_i64() }
#[inline]
fn read_i32(&mut self) -> i32 { self.opaque.read_i32() }
#[inline]
fn read_i16(&mut self) -> i16 { self.opaque.read_i16() }
#[inline]
fn read_raw_bytes(&mut self, len: usize) -> &[u8] {
self.opaque.read_raw_bytes(len)
}
#[inline]
fn peek_byte(&self) -> u8 { self.opaque.peek_byte() }
#[inline]
fn position(&self) -> usize { self.opaque.position() }
}
}implement_ty_decoder!(BlobDecodeContext<'a>);
700}
701
702impl MetadataBlob {
703 pub(crate) fn check_compatibility(
704 &self,
705 cfg_version: &'static str,
706 ) -> Result<(), Option<String>> {
707 if !self.starts_with(METADATA_HEADER) {
708 if self.starts_with(b"rust") {
709 return Err(Some("<unknown rustc version>".to_owned()));
710 }
711 return Err(None);
712 }
713
714 let found_version =
715 LazyValue::<String>::from_position(NonZero::new(METADATA_HEADER.len() + 8).unwrap())
716 .decode(self);
717 if rustc_version(cfg_version) != found_version {
718 return Err(Some(found_version));
719 }
720
721 Ok(())
722 }
723
724 fn root_pos(&self) -> NonZero<usize> {
725 let offset = METADATA_HEADER.len();
726 let pos_bytes = self[offset..][..8].try_into().unwrap();
727 let pos = u64::from_le_bytes(pos_bytes);
728 NonZero::new(pos as usize).unwrap()
729 }
730
731 pub(crate) fn get_header(&self) -> CrateHeader {
732 let pos = self.root_pos();
733 LazyValue::<CrateHeader>::from_position(pos).decode(self)
734 }
735
736 pub(crate) fn get_root(&self) -> CrateRoot {
737 let pos = self.root_pos();
738 LazyValue::<CrateRoot>::from_position(pos).decode(self)
739 }
740
741 pub(crate) fn list_crate_metadata(
742 &self,
743 out: &mut dyn io::Write,
744 ls_kinds: &[String],
745 ) -> io::Result<()> {
746 let root = self.get_root();
747
748 let all_ls_kinds = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["root".to_owned(), "lang_items".to_owned(), "features".to_owned(),
"items".to_owned()]))vec![
749 "root".to_owned(),
750 "lang_items".to_owned(),
751 "features".to_owned(),
752 "items".to_owned(),
753 ];
754 let ls_kinds = if ls_kinds.contains(&"all".to_owned()) { &all_ls_kinds } else { ls_kinds };
755
756 for kind in ls_kinds {
757 match &**kind {
758 "root" => {
759 out.write_fmt(format_args!("Crate info:\n"))writeln!(out, "Crate info:")?;
760 out.write_fmt(format_args!("name {0}{1}\n", root.name(), root.extra_filename))writeln!(out, "name {}{}", root.name(), root.extra_filename)?;
761 out.write_fmt(format_args!("hash {0} stable_crate_id {1:?}\n", root.hash(),
root.stable_crate_id))writeln!(
762 out,
763 "hash {} stable_crate_id {:?}",
764 root.hash(),
765 root.stable_crate_id
766 )?;
767 out.write_fmt(format_args!("proc_macro {0:?}\n",
root.proc_macro_data.is_some()))writeln!(out, "proc_macro {:?}", root.proc_macro_data.is_some())?;
768 out.write_fmt(format_args!("triple {0}\n", root.header.triple.tuple()))writeln!(out, "triple {}", root.header.triple.tuple())?;
769 out.write_fmt(format_args!("edition {0}\n", root.edition))writeln!(out, "edition {}", root.edition)?;
770 out.write_fmt(format_args!("symbol_mangling_version {0:?}\n",
root.symbol_mangling_version))writeln!(out, "symbol_mangling_version {:?}", root.symbol_mangling_version)?;
771 out.write_fmt(format_args!("required_panic_strategy {0:?} panic_in_drop_strategy {1:?}\n",
root.required_panic_strategy, root.panic_in_drop_strategy))writeln!(
772 out,
773 "required_panic_strategy {:?} panic_in_drop_strategy {:?}",
774 root.required_panic_strategy, root.panic_in_drop_strategy
775 )?;
776 out.write_fmt(format_args!("has_global_allocator {0} has_alloc_error_handler {1} has_panic_handler {2} has_default_lib_allocator {3}\n",
root.has_global_allocator, root.has_alloc_error_handler,
root.has_panic_handler, root.has_default_lib_allocator))writeln!(
777 out,
778 "has_global_allocator {} has_alloc_error_handler {} has_panic_handler {} has_default_lib_allocator {}",
779 root.has_global_allocator,
780 root.has_alloc_error_handler,
781 root.has_panic_handler,
782 root.has_default_lib_allocator
783 )?;
784 out.write_fmt(format_args!("compiler_builtins {0} needs_allocator {1} needs_panic_runtime {2} no_builtins {3} panic_runtime {4} profiler_runtime {5}\n",
root.compiler_builtins, root.needs_allocator,
root.needs_panic_runtime, root.no_builtins, root.panic_runtime,
root.profiler_runtime))writeln!(
785 out,
786 "compiler_builtins {} needs_allocator {} needs_panic_runtime {} no_builtins {} panic_runtime {} profiler_runtime {}",
787 root.compiler_builtins,
788 root.needs_allocator,
789 root.needs_panic_runtime,
790 root.no_builtins,
791 root.panic_runtime,
792 root.profiler_runtime
793 )?;
794
795 out.write_fmt(format_args!("=External Dependencies=\n"))writeln!(out, "=External Dependencies=")?;
796 let dylib_dependency_formats =
797 root.dylib_dependency_formats.decode(self).collect::<Vec<_>>();
798 for (i, dep) in root.crate_deps.decode(self).enumerate() {
799 let CrateDep { name, extra_filename, hash, host_hash, kind, is_private } =
800 dep;
801 let number = i + 1;
802
803 out.write_fmt(format_args!("{2} {3}{4} hash {5} host_hash {6:?} kind {7:?} {0}{1}\n",
if is_private { "private" } else { "public" },
if dylib_dependency_formats.is_empty() {
String::new()
} else {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" linkage {0:?}",
dylib_dependency_formats[i]))
})
}, number, name, extra_filename, hash, host_hash, kind))writeln!(
804 out,
805 "{number} {name}{extra_filename} hash {hash} host_hash {host_hash:?} kind {kind:?} {privacy}{linkage}",
806 privacy = if is_private { "private" } else { "public" },
807 linkage = if dylib_dependency_formats.is_empty() {
808 String::new()
809 } else {
810 format!(" linkage {:?}", dylib_dependency_formats[i])
811 }
812 )?;
813 }
814 out.write_fmt(format_args!("\n"))write!(out, "\n")?;
815 }
816
817 "lang_items" => {
818 out.write_fmt(format_args!("=Lang items=\n"))writeln!(out, "=Lang items=")?;
819 for (id, lang_item) in root.lang_items.decode(self) {
820 out.write_fmt(format_args!("{0} = crate{1}\n", lang_item.name(),
DefPath::make(LOCAL_CRATE, id,
|parent|
root.tables.def_keys.get(self,
parent).unwrap().decode(self)).to_string_no_crate_verbose()))writeln!(
821 out,
822 "{} = crate{}",
823 lang_item.name(),
824 DefPath::make(LOCAL_CRATE, id, |parent| root
825 .tables
826 .def_keys
827 .get(self, parent)
828 .unwrap()
829 .decode(self))
830 .to_string_no_crate_verbose()
831 )?;
832 }
833 for lang_item in root.lang_items_missing.decode(self) {
834 out.write_fmt(format_args!("{0} = <missing>\n", lang_item.name()))writeln!(out, "{} = <missing>", lang_item.name())?;
835 }
836 out.write_fmt(format_args!("\n"))write!(out, "\n")?;
837 }
838
839 "features" => {
840 out.write_fmt(format_args!("=Lib features=\n"))writeln!(out, "=Lib features=")?;
841 for (feature, since) in root.lib_features.decode(self) {
842 out.write_fmt(format_args!("{0}{1}\n", feature,
if let FeatureStability::AcceptedSince(since) = since {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" since {0}", since))
})
} else { String::new() }))writeln!(
843 out,
844 "{}{}",
845 feature,
846 if let FeatureStability::AcceptedSince(since) = since {
847 format!(" since {since}")
848 } else {
849 String::new()
850 }
851 )?;
852 }
853 out.write_fmt(format_args!("\n"))write!(out, "\n")?;
854 }
855
856 "items" => {
857 out.write_fmt(format_args!("=Items=\n"))writeln!(out, "=Items=")?;
858
859 fn print_item(
860 blob: &MetadataBlob,
861 out: &mut dyn io::Write,
862 item: DefIndex,
863 indent: usize,
864 ) -> io::Result<()> {
865 let root = blob.get_root();
866
867 let def_kind = root.tables.def_kind.get(blob, item).unwrap();
868 let def_key = root.tables.def_keys.get(blob, item).unwrap().decode(blob);
869 #[allow(rustc::symbol_intern_string_literal)]
870 let def_name = if item == CRATE_DEF_INDEX {
871 kw::Crate
872 } else {
873 def_key
874 .disambiguated_data
875 .data
876 .get_opt_name()
877 .unwrap_or_else(|| Symbol::intern("???"))
878 };
879 let visibility =
880 root.tables.visibility.get(blob, item).unwrap().decode(blob).map_id(
881 |index| {
882 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("crate{0}",
DefPath::make(LOCAL_CRATE, index,
|parent|
root.tables.def_keys.get(blob,
parent).unwrap().decode(blob)).to_string_no_crate_verbose()))
})format!(
883 "crate{}",
884 DefPath::make(LOCAL_CRATE, index, |parent| root
885 .tables
886 .def_keys
887 .get(blob, parent)
888 .unwrap()
889 .decode(blob))
890 .to_string_no_crate_verbose()
891 )
892 },
893 );
894 out.write_fmt(format_args!("{3: <4$}{0:?} {1:?} {2} {{", visibility, def_kind,
def_name, "", indent))write!(
895 out,
896 "{nil: <indent$}{:?} {:?} {} {{",
897 visibility,
898 def_kind,
899 def_name,
900 nil = "",
901 )?;
902
903 if let Some(children) =
904 root.tables.module_children_non_reexports.get(blob, item)
905 {
906 out.write_fmt(format_args!("\n"))write!(out, "\n")?;
907 for child in children.decode(blob) {
908 print_item(blob, out, child, indent + 4)?;
909 }
910 out.write_fmt(format_args!("{0: <1$}}}\n", "", indent))writeln!(out, "{nil: <indent$}}}", nil = "")?;
911 } else {
912 out.write_fmt(format_args!("}}\n"))writeln!(out, "}}")?;
913 }
914
915 Ok(())
916 }
917
918 print_item(self, out, CRATE_DEF_INDEX, 0)?;
919
920 out.write_fmt(format_args!("\n"))write!(out, "\n")?;
921 }
922
923 _ => {
924 out.write_fmt(format_args!("unknown -Zls kind. allowed values are: all, root, lang_items, features, items\n"))writeln!(
925 out,
926 "unknown -Zls kind. allowed values are: all, root, lang_items, features, items"
927 )?;
928 }
929 }
930 }
931
932 Ok(())
933 }
934
935 pub(crate) fn get_proc_macro_info(&self) -> Vec<ProcMacroKind> {
936 self.get_root()
937 .proc_macro_data
938 .unwrap()
939 .macros
940 .decode(self)
941 .map(|(_id, kind)| kind.decode(self))
942 .collect::<Vec<_>>()
943 }
944}
945
946impl CrateRoot {
947 pub(crate) fn is_proc_macro_crate(&self) -> bool {
948 self.proc_macro_data.is_some()
949 }
950
951 pub(crate) fn name(&self) -> Symbol {
952 self.header.name
953 }
954
955 pub(crate) fn hash(&self) -> Svh {
956 self.header.hash
957 }
958
959 pub(crate) fn stable_crate_id(&self) -> StableCrateId {
960 self.stable_crate_id
961 }
962
963 pub(crate) fn decode_crate_deps<'a>(
964 &self,
965 metadata: &'a MetadataBlob,
966 ) -> impl ExactSizeIterator<Item = CrateDep> {
967 self.crate_deps.decode(metadata)
968 }
969
970 pub(crate) fn decode_target_modifiers<'a>(
971 &self,
972 metadata: &'a MetadataBlob,
973 ) -> impl ExactSizeIterator<Item = TargetModifier> {
974 self.target_modifiers.decode(metadata)
975 }
976
977 pub(crate) fn decode_denied_partial_mitigations<'a>(
978 &self,
979 metadata: &'a MetadataBlob,
980 ) -> impl ExactSizeIterator<Item = DeniedPartialMitigation> {
981 self.denied_partial_mitigations.decode(metadata)
982 }
983}
984
985impl CrateMetadata {
986 fn missing(&self, descr: &str, id: DefIndex) -> ! {
987 ::rustc_middle::util::bug::bug_fmt(format_args!("missing `{1}` for {0:?}",
self.local_def_id(id), descr))bug!("missing `{descr}` for {:?}", self.local_def_id(id))
988 }
989
990 fn raw_proc_macro(&self, tcx: TyCtxt<'_>, id: DefIndex) -> (ProcMacroClient, ProcMacroKind) {
991 let (pos, (_id, kind)) = self
994 .root
995 .proc_macro_data
996 .as_ref()
997 .unwrap()
998 .macros
999 .decode((self, tcx))
1000 .enumerate()
1001 .find(|(_pos, (i, _))| *i == id)
1002 .unwrap();
1003 (self.raw_proc_macros.unwrap()[pos], kind.decode((self, tcx)))
1004 }
1005
1006 fn opt_item_name(&self, item_index: DefIndex) -> Option<Symbol> {
1007 let def_key = self.def_key(item_index);
1008 def_key.disambiguated_data.data.get_opt_name().or_else(|| {
1009 if def_key.disambiguated_data.data == DefPathData::Ctor {
1010 let parent_index = def_key.parent.expect("no parent for a constructor");
1011 self.def_key(parent_index).disambiguated_data.data.get_opt_name()
1012 } else {
1013 None
1014 }
1015 })
1016 }
1017
1018 fn item_name(&self, item_index: DefIndex) -> Symbol {
1019 self.opt_item_name(item_index).expect("no encoded ident for item")
1020 }
1021
1022 fn opt_item_ident(&self, tcx: TyCtxt<'_>, item_index: DefIndex) -> Option<Ident> {
1023 let name = self.opt_item_name(item_index)?;
1024 let span = self
1025 .root
1026 .tables
1027 .def_ident_span
1028 .get(self, item_index)
1029 .unwrap_or_else(|| self.missing("def_ident_span", item_index))
1030 .decode((self, tcx));
1031 Some(Ident::new(name, span))
1032 }
1033
1034 fn item_ident(&self, tcx: TyCtxt<'_>, item_index: DefIndex) -> Ident {
1035 self.opt_item_ident(tcx, item_index).expect("no encoded ident for item")
1036 }
1037
1038 #[inline]
1039 pub(super) fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum {
1040 if cnum == LOCAL_CRATE { self.cnum } else { self.cnum_map[cnum] }
1041 }
1042
1043 fn def_kind(&self, item_id: DefIndex) -> DefKind {
1044 self.root
1045 .tables
1046 .def_kind
1047 .get(self, item_id)
1048 .unwrap_or_else(|| self.missing("def_kind", item_id))
1049 }
1050
1051 fn get_span(&self, tcx: TyCtxt<'_>, index: DefIndex) -> Span {
1052 self.root
1053 .tables
1054 .def_span
1055 .get(self, index)
1056 .unwrap_or_else(|| self.missing("def_span", index))
1057 .decode((self, tcx))
1058 }
1059
1060 fn load_proc_macro<'tcx>(&self, tcx: TyCtxt<'tcx>, id: DefIndex) -> SyntaxExtension {
1061 let (name, kind, helper_attrs) = match self.raw_proc_macro(tcx, id) {
1062 (client, ProcMacroKind::CustomDerive { trait_name, attributes }) => {
1063 let helper_attrs =
1064 attributes.into_iter().map(|attr| Symbol::intern(&attr)).collect();
1065 (
1066 trait_name,
1067 SyntaxExtensionKind::Derive(Arc::new(DeriveProcMacro { client })),
1068 helper_attrs,
1069 )
1070 }
1071 (client, ProcMacroKind::Attr { name }) => {
1072 (name, SyntaxExtensionKind::Attr(Arc::new(AttrProcMacro { client })), Vec::new())
1073 }
1074 (client, ProcMacroKind::Bang { name }) => {
1075 (name, SyntaxExtensionKind::Bang(Arc::new(BangProcMacro { client })), Vec::new())
1076 }
1077 };
1078
1079 let sess = tcx.sess;
1080 let attrs: Vec<_> = self.get_item_attrs(tcx, id).collect();
1081 SyntaxExtension::new(
1082 sess,
1083 kind,
1084 self.get_span(tcx, id),
1085 helper_attrs,
1086 self.root.edition,
1087 Symbol::intern(&name),
1088 &attrs,
1089 false,
1090 )
1091 }
1092
1093 fn get_variant(
1094 &self,
1095 tcx: TyCtxt<'_>,
1096 kind: DefKind,
1097 index: DefIndex,
1098 parent_did: DefId,
1099 ) -> (VariantIdx, ty::VariantDef) {
1100 let adt_kind = match kind {
1101 DefKind::Variant => ty::AdtKind::Enum,
1102 DefKind::Struct => ty::AdtKind::Struct,
1103 DefKind::Union => ty::AdtKind::Union,
1104 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
1105 };
1106
1107 let data = self.root.tables.variant_data.get(self, index).unwrap().decode((self, tcx));
1108
1109 let variant_did =
1110 if adt_kind == ty::AdtKind::Enum { Some(self.local_def_id(index)) } else { None };
1111 let ctor = data.ctor.map(|(kind, index)| (kind, self.local_def_id(index)));
1112
1113 (
1114 data.idx,
1115 ty::VariantDef::new(
1116 self.item_name(index),
1117 variant_did,
1118 ctor,
1119 data.discr,
1120 self.get_associated_item_or_field_def_ids(tcx, index)
1121 .map(|did| ty::FieldDef {
1122 did,
1123 name: self.item_name(did.index),
1124 vis: self.get_visibility(tcx, did.index),
1125 safety: self.get_safety(did.index),
1126 value: self.get_default_field(tcx, did.index),
1127 })
1128 .collect(),
1129 parent_did,
1130 None,
1131 data.is_non_exhaustive,
1132 ),
1133 )
1134 }
1135
1136 fn get_adt_def<'tcx>(&self, tcx: TyCtxt<'tcx>, item_id: DefIndex) -> ty::AdtDef<'tcx> {
1137 let kind = self.def_kind(item_id);
1138 let did = self.local_def_id(item_id);
1139
1140 let adt_kind = match kind {
1141 DefKind::Enum => ty::AdtKind::Enum,
1142 DefKind::Struct => ty::AdtKind::Struct,
1143 DefKind::Union => ty::AdtKind::Union,
1144 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("get_adt_def called on a non-ADT {0:?}",
did))bug!("get_adt_def called on a non-ADT {:?}", did),
1145 };
1146 let repr = self.root.tables.repr_options.get(self, item_id).unwrap().decode((self, tcx));
1147
1148 let mut variants: Vec<_> = if let ty::AdtKind::Enum = adt_kind {
1149 self.root
1150 .tables
1151 .module_children_non_reexports
1152 .get(self, item_id)
1153 .expect("variants are not encoded for an enum")
1154 .decode((self, tcx))
1155 .filter_map(|index| {
1156 let kind = self.def_kind(index);
1157 match kind {
1158 DefKind::Ctor(..) => None,
1159 _ => Some(self.get_variant(tcx, kind, index, did)),
1160 }
1161 })
1162 .collect()
1163 } else {
1164 std::iter::once(self.get_variant(tcx, kind, item_id, did)).collect()
1165 };
1166
1167 variants.sort_by_key(|(idx, _)| *idx);
1168
1169 tcx.mk_adt_def(
1170 did,
1171 adt_kind,
1172 variants.into_iter().map(|(_, variant)| variant).collect(),
1173 repr,
1174 )
1175 }
1176
1177 fn get_visibility(&self, tcx: TyCtxt<'_>, id: DefIndex) -> Visibility<ModId> {
1178 self.root
1179 .tables
1180 .visibility
1181 .get(self, id)
1182 .unwrap_or_else(|| self.missing("visibility", id))
1183 .decode((self, tcx))
1184 .map_id(|index| ModId::new_unchecked(self.local_def_id(index)))
1185 }
1186
1187 fn get_safety(&self, id: DefIndex) -> Safety {
1188 self.root.tables.safety.get(self, id)
1189 }
1190
1191 fn get_default_field(&self, tcx: TyCtxt<'_>, id: DefIndex) -> Option<DefId> {
1192 self.root.tables.default_fields.get(self, id).map(|d| d.decode((self, tcx)))
1193 }
1194
1195 fn get_expn_that_defined(&self, tcx: TyCtxt<'_>, id: DefIndex) -> ExpnId {
1196 self.root
1197 .tables
1198 .expn_that_defined
1199 .get(self, id)
1200 .unwrap_or_else(|| self.missing("expn_that_defined", id))
1201 .decode((self, tcx))
1202 }
1203
1204 fn get_debugger_visualizers(&self, tcx: TyCtxt<'_>) -> Vec<DebuggerVisualizerFile> {
1205 self.root.debugger_visualizers.decode((self, tcx)).collect::<Vec<_>>()
1206 }
1207
1208 fn get_lib_features(&self, tcx: TyCtxt<'_>) -> LibFeatures {
1210 LibFeatures {
1211 stability: self
1212 .root
1213 .lib_features
1214 .decode((self, tcx))
1215 .map(|(sym, stab)| (sym, (stab, DUMMY_SP)))
1216 .collect(),
1217 }
1218 }
1219
1220 fn get_stability_implications<'tcx>(&self, tcx: TyCtxt<'tcx>) -> &'tcx [(Symbol, Symbol)] {
1224 tcx.arena.alloc_from_iter(self.root.stability_implications.decode((self, tcx)))
1225 }
1226
1227 fn get_lang_items<'tcx>(&self, tcx: TyCtxt<'tcx>) -> &'tcx [(DefId, LangItem)] {
1229 tcx.arena.alloc_from_iter(
1230 self.root
1231 .lang_items
1232 .decode((self, tcx))
1233 .map(move |(def_index, index)| (self.local_def_id(def_index), index)),
1234 )
1235 }
1236
1237 fn get_stripped_cfg_items<'tcx>(
1238 &self,
1239 tcx: TyCtxt<'tcx>,
1240 cnum: CrateNum,
1241 ) -> &'tcx [StrippedCfgItem] {
1242 let item_names = self
1243 .root
1244 .stripped_cfg_items
1245 .decode((self, tcx))
1246 .map(|item| item.map_scope_id(|index| DefId { krate: cnum, index }));
1247 tcx.arena.alloc_from_iter(item_names)
1248 }
1249
1250 fn get_diagnostic_items(&self, tcx: TyCtxt<'_>) -> DiagnosticItems {
1252 let mut id_to_name = DefIdMap::default();
1253 let name_to_id = self
1254 .root
1255 .diagnostic_items
1256 .decode((self, tcx))
1257 .map(|(name, def_index)| {
1258 let id = self.local_def_id(def_index);
1259 id_to_name.insert(id, name);
1260 (name, id)
1261 })
1262 .collect();
1263 DiagnosticItems { id_to_name, name_to_id }
1264 }
1265
1266 fn get_mod_child(&self, tcx: TyCtxt<'_>, id: DefIndex) -> ModChild {
1267 let ident = self.item_ident(tcx, id);
1268 let res = Res::Def(self.def_kind(id), self.local_def_id(id));
1269 let vis = self.get_visibility(tcx, id);
1270
1271 ModChild { ident, res, vis, reexport_chain: Default::default() }
1272 }
1273
1274 fn get_module_children(&self, tcx: TyCtxt<'_>, id: DefIndex) -> impl Iterator<Item = ModChild> {
1283 gen move {
1284 if let Some(data) = &self.root.proc_macro_data {
1285 if id == CRATE_DEF_INDEX {
1288 for (child_index, _) in data.macros.decode((self, tcx)) {
1289 yield self.get_mod_child(tcx, child_index);
1290 }
1291 }
1292 } else {
1293 let non_reexports = self.root.tables.module_children_non_reexports.get(self, id);
1295 let non_reexports =
1296 non_reexports.expect("provided `DefIndex` must refer to a module-like item");
1297 for child_index in non_reexports.decode((self, tcx)) {
1298 yield self.get_mod_child(tcx, child_index);
1299 }
1300
1301 let reexports = self.root.tables.module_children_reexports.get(self, id);
1302 if !reexports.is_default() {
1303 for reexport in reexports.decode((self, tcx)) {
1304 yield reexport;
1305 }
1306 }
1307 }
1308 }
1309 }
1310
1311 fn get_ambig_module_children(
1312 &self,
1313 tcx: TyCtxt<'_>,
1314 id: DefIndex,
1315 ) -> impl Iterator<Item = AmbigModChild> {
1316 gen move {
1317 let children = self.root.tables.ambig_module_children.get(self, id);
1318 if !children.is_default() {
1319 for child in children.decode((self, tcx)) {
1320 yield child;
1321 }
1322 }
1323 }
1324 }
1325
1326 fn is_item_mir_available(&self, id: DefIndex) -> bool {
1327 self.root.tables.optimized_mir.get(self, id).is_some()
1328 }
1329
1330 fn get_fn_has_self_parameter(&self, tcx: TyCtxt<'_>, id: DefIndex) -> bool {
1331 self.root
1332 .tables
1333 .fn_arg_idents
1334 .get(self, id)
1335 .expect("argument names not encoded for a function")
1336 .decode((self, tcx))
1337 .nth(0)
1338 .is_some_and(|ident| #[allow(non_exhaustive_omitted_patterns)] match ident {
Some(Ident { name: kw::SelfLower, .. }) => true,
_ => false,
}matches!(ident, Some(Ident { name: kw::SelfLower, .. })))
1339 }
1340
1341 fn get_associated_item_or_field_def_ids(
1342 &self,
1343 tcx: TyCtxt<'_>,
1344 id: DefIndex,
1345 ) -> impl Iterator<Item = DefId> {
1346 self.root
1347 .tables
1348 .associated_item_or_field_def_ids
1349 .get(self, id)
1350 .unwrap_or_else(|| self.missing("associated_item_or_field_def_ids", id))
1351 .decode((self, tcx))
1352 .map(move |child_index| self.local_def_id(child_index))
1353 }
1354
1355 fn get_associated_item(&self, tcx: TyCtxt<'_>, id: DefIndex) -> ty::AssocItem {
1356 let kind = match self.def_kind(id) {
1357 DefKind::AssocConst { is_type_const } => {
1358 ty::AssocKind::Const { name: self.item_name(id), is_type_const }
1359 }
1360 DefKind::AssocFn => ty::AssocKind::Fn {
1361 name: self.item_name(id),
1362 has_self: self.get_fn_has_self_parameter(tcx, id),
1363 },
1364 DefKind::AssocTy => {
1365 let data = if let Some(rpitit_info) = self.root.tables.opt_rpitit_info.get(self, id)
1366 {
1367 ty::AssocTypeData::Rpitit(rpitit_info.decode((self, tcx)))
1368 } else {
1369 ty::AssocTypeData::Normal(self.item_name(id))
1370 };
1371 ty::AssocKind::Type { data }
1372 }
1373 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("cannot get associated-item of `{0:?}`",
self.def_key(id)))bug!("cannot get associated-item of `{:?}`", self.def_key(id)),
1374 };
1375 let container = self.root.tables.assoc_container.get(self, id).unwrap().decode((self, tcx));
1376
1377 ty::AssocItem { kind, def_id: self.local_def_id(id), container }
1378 }
1379
1380 fn get_ctor(&self, tcx: TyCtxt<'_>, node_id: DefIndex) -> Option<(CtorKind, DefId)> {
1381 match self.def_kind(node_id) {
1382 DefKind::Struct | DefKind::Variant => {
1383 let vdata =
1384 self.root.tables.variant_data.get(self, node_id).unwrap().decode((self, tcx));
1385 vdata.ctor.map(|(kind, index)| (kind, self.local_def_id(index)))
1386 }
1387 _ => None,
1388 }
1389 }
1390
1391 fn get_item_attrs(
1392 &self,
1393 tcx: TyCtxt<'_>,
1394 id: DefIndex,
1395 ) -> impl Iterator<Item = hir::Attribute> {
1396 self.root
1397 .tables
1398 .attributes
1399 .get(self, id)
1400 .unwrap_or_else(|| {
1401 let def_key = self.def_key(id);
1405 {
match (&def_key.disambiguated_data.data, &DefPathData::Ctor) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(def_key.disambiguated_data.data, DefPathData::Ctor);
1406 let parent_id = def_key.parent.expect("no parent for a constructor");
1407 self.root
1408 .tables
1409 .attributes
1410 .get(self, parent_id)
1411 .expect("no encoded attributes for a structure or variant")
1412 })
1413 .decode((self, tcx))
1414 }
1415
1416 fn get_inherent_implementations_for_type<'tcx>(
1417 &self,
1418 tcx: TyCtxt<'tcx>,
1419 id: DefIndex,
1420 ) -> &'tcx [DefId] {
1421 tcx.arena.alloc_from_iter(
1422 self.root
1423 .tables
1424 .inherent_impls
1425 .get(self, id)
1426 .decode((self, tcx))
1427 .map(|index| self.local_def_id(index)),
1428 )
1429 }
1430
1431 fn get_traits(&self, tcx: TyCtxt<'_>) -> impl Iterator<Item = DefId> {
1433 self.root.traits.decode((self, tcx)).map(move |index| self.local_def_id(index))
1434 }
1435
1436 fn get_trait_impls(&self, tcx: TyCtxt<'_>) -> impl Iterator<Item = DefId> {
1438 self.trait_impls.values().flat_map(move |impls| {
1439 impls.decode((self, tcx)).map(move |(impl_index, _)| self.local_def_id(impl_index))
1440 })
1441 }
1442
1443 fn get_incoherent_impls<'tcx>(&self, tcx: TyCtxt<'tcx>, simp: SimplifiedType) -> &'tcx [DefId] {
1444 if let Some(impls) = self.incoherent_impls.get(&simp) {
1445 tcx.arena.alloc_from_iter(impls.decode((self, tcx)).map(|idx| self.local_def_id(idx)))
1446 } else {
1447 &[]
1448 }
1449 }
1450
1451 fn get_implementations_of_trait<'tcx>(
1452 &self,
1453 tcx: TyCtxt<'tcx>,
1454 trait_def_id: DefId,
1455 ) -> &'tcx [(DefId, Option<SimplifiedType>)] {
1456 if self.trait_impls.is_empty() {
1457 return &[];
1458 }
1459
1460 let key = match self.reverse_translate_def_id(trait_def_id) {
1463 Some(def_id) => (def_id.krate.as_u32(), def_id.index),
1464 None => return &[],
1465 };
1466
1467 if let Some(impls) = self.trait_impls.get(&key) {
1468 tcx.arena.alloc_from_iter(
1469 impls
1470 .decode((self, tcx))
1471 .map(|(idx, simplified_self_ty)| (self.local_def_id(idx), simplified_self_ty)),
1472 )
1473 } else {
1474 &[]
1475 }
1476 }
1477
1478 fn get_native_libraries(&self, tcx: TyCtxt<'_>) -> impl Iterator<Item = NativeLib> {
1479 self.root.native_libraries.decode((self, tcx))
1480 }
1481
1482 fn get_proc_macro_quoted_span(&self, tcx: TyCtxt<'_>, index: usize) -> Span {
1483 self.root
1484 .tables
1485 .proc_macro_quoted_spans
1486 .get(self, index)
1487 .unwrap_or_else(|| {
::core::panicking::panic_fmt(format_args!("Missing proc macro quoted span: {0:?}",
index));
}panic!("Missing proc macro quoted span: {index:?}"))
1488 .decode((self, tcx))
1489 }
1490
1491 fn get_foreign_modules(&self, tcx: TyCtxt<'_>) -> impl Iterator<Item = ForeignModule> {
1492 self.root.foreign_modules.decode((self, tcx))
1493 }
1494
1495 fn get_dylib_dependency_formats<'tcx>(
1496 &self,
1497 tcx: TyCtxt<'tcx>,
1498 ) -> &'tcx [(CrateNum, LinkagePreference)] {
1499 tcx.arena.alloc_from_iter(
1500 self.root.dylib_dependency_formats.decode((self, tcx)).enumerate().flat_map(
1501 |(i, link)| {
1502 let cnum = CrateNum::new(i + 1); link.map(|link| (self.cnum_map[cnum], link))
1504 },
1505 ),
1506 )
1507 }
1508
1509 fn get_externally_implementable_items(
1510 &self,
1511 tcx: TyCtxt<'_>,
1512 ) -> impl Iterator<Item = EiiMapEncodedKeyValue> {
1513 self.root.externally_implementable_items.decode((self, tcx))
1514 }
1515
1516 fn get_missing_lang_items<'tcx>(&self, tcx: TyCtxt<'tcx>) -> &'tcx [LangItem] {
1517 tcx.arena.alloc_from_iter(self.root.lang_items_missing.decode((self, tcx)))
1518 }
1519
1520 fn get_exportable_items(&self, tcx: TyCtxt<'_>) -> impl Iterator<Item = DefId> {
1521 self.root.exportable_items.decode((self, tcx)).map(move |index| self.local_def_id(index))
1522 }
1523
1524 fn get_stable_order_of_exportable_impls(
1525 &self,
1526 tcx: TyCtxt<'_>,
1527 ) -> impl Iterator<Item = (DefId, usize)> {
1528 self.root
1529 .stable_order_of_exportable_impls
1530 .decode((self, tcx))
1531 .map(move |v| (self.local_def_id(v.0), v.1))
1532 }
1533
1534 fn exported_non_generic_symbols<'tcx>(
1535 &self,
1536 tcx: TyCtxt<'tcx>,
1537 ) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportInfo)] {
1538 tcx.arena.alloc_from_iter(self.root.exported_non_generic_symbols.decode((self, tcx)))
1539 }
1540
1541 fn exported_generic_symbols<'tcx>(
1542 &self,
1543 tcx: TyCtxt<'tcx>,
1544 ) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportInfo)] {
1545 tcx.arena.alloc_from_iter(self.root.exported_generic_symbols.decode((self, tcx)))
1546 }
1547
1548 fn get_macro(&self, tcx: TyCtxt<'_>, id: DefIndex) -> ast::MacroDef {
1549 match self.def_kind(id) {
1550 DefKind::Macro(_) => {
1551 let macro_rules = self.root.tables.is_macro_rules.get(self, id);
1552 let body =
1553 self.root.tables.macro_definition.get(self, id).unwrap().decode((self, tcx));
1554 ast::MacroDef { macro_rules, body: Box::new(body), eii_declaration: None }
1555 }
1556 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
1557 }
1558 }
1559
1560 #[inline]
1561 fn def_key(&self, index: DefIndex) -> DefKey {
1562 *self.def_key_cache.lock().entry(index).or_insert_with(|| {
1563 self.root.tables.def_keys.get(&self.blob, index).unwrap().decode(&self.blob)
1564 })
1565 }
1566
1567 fn def_path(&self, id: DefIndex) -> DefPath {
1569 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/rmeta/decoder.rs:1569",
"rustc_metadata::rmeta::decoder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/rmeta/decoder.rs"),
::tracing_core::__macro_support::Option::Some(1569u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::decoder"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("def_path(cnum={0:?}, id={1:?})",
self.cnum, id) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("def_path(cnum={:?}, id={:?})", self.cnum, id);
1570 DefPath::make(self.cnum, id, |parent| self.def_key(parent))
1571 }
1572
1573 #[inline]
1574 fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
1575 let fingerprint = Fingerprint::new(
1579 self.root.stable_crate_id.as_u64(),
1580 self.root.tables.def_path_hashes.get(&self.blob, index),
1581 );
1582 DefPathHash::new(self.root.stable_crate_id, fingerprint.split().1)
1583 }
1584
1585 #[inline]
1586 fn def_path_hash_to_def_index(&self, hash: DefPathHash) -> Option<DefIndex> {
1587 self.def_path_hash_map.def_path_hash_to_def_index(&hash)
1588 }
1589
1590 fn expn_hash_to_expn_id(&self, tcx: TyCtxt<'_>, index_guess: u32, hash: ExpnHash) -> ExpnId {
1591 let index_guess = ExpnIndex::from_u32(index_guess);
1592 let old_hash =
1593 self.root.expn_hashes.get(self, index_guess).map(|lazy| lazy.decode((self, tcx)));
1594
1595 let index = if old_hash == Some(hash) {
1596 index_guess
1600 } else {
1601 let map = self.expn_hash_map.get_or_init(|| {
1605 let end_id = self.root.expn_hashes.size() as u32;
1606 let mut map =
1607 UnhashMap::with_capacity_and_hasher(end_id as usize, Default::default());
1608 for i in 0..end_id {
1609 let i = ExpnIndex::from_u32(i);
1610 if let Some(hash) = self.root.expn_hashes.get(self, i) {
1611 map.insert(hash.decode((self, tcx)), i);
1612 }
1613 }
1614 map
1615 });
1616 map[&hash]
1617 };
1618
1619 let data = self.root.expn_data.get(self, index).unwrap().decode((self, tcx));
1620 rustc_span::hygiene::register_expn_id(self.cnum, index, data, hash)
1621 }
1622
1623 fn imported_source_file(&self, tcx: TyCtxt<'_>, source_file_index: u32) -> ImportedSourceFile {
1649 fn filter<'a>(
1650 tcx: TyCtxt<'_>,
1651 real_source_base_dir: &Option<PathBuf>,
1652 path: Option<&'a Path>,
1653 ) -> Option<&'a Path> {
1654 path.filter(|_| {
1655 real_source_base_dir.is_some()
1657 && tcx.sess.opts.unstable_opts.translate_remapped_path_to_local_path
1659 })
1660 .filter(|virtual_dir| {
1661 !tcx.sess.opts.remap_path_prefix.iter().any(|(_from, to)| to == virtual_dir)
1665 })
1666 }
1667
1668 let try_to_translate_virtual_to_real =
1669 |virtual_source_base_dir: Option<&str>,
1670 real_source_base_dir: &Option<PathBuf>,
1671 name: &mut rustc_span::FileName| {
1672 let virtual_source_base_dir = [
1673 filter(tcx, real_source_base_dir, virtual_source_base_dir.map(Path::new)),
1674 filter(
1675 tcx,
1676 real_source_base_dir,
1677 tcx.sess.opts.unstable_opts.simulate_remapped_rust_src_base.as_deref(),
1678 ),
1679 ];
1680
1681 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/rmeta/decoder.rs:1681",
"rustc_metadata::rmeta::decoder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/rmeta/decoder.rs"),
::tracing_core::__macro_support::Option::Some(1681u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::decoder"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("try_to_translate_virtual_to_real(name={0:?}): virtual_source_base_dir={1:?}, real_source_base_dir={2:?}",
name, virtual_source_base_dir, real_source_base_dir) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
1682 "try_to_translate_virtual_to_real(name={:?}): \
1683 virtual_source_base_dir={:?}, real_source_base_dir={:?}",
1684 name, virtual_source_base_dir, real_source_base_dir,
1685 );
1686
1687 for virtual_dir in virtual_source_base_dir.iter().flatten() {
1688 if let Some(real_dir) = &real_source_base_dir
1689 && let rustc_span::FileName::Real(old_name) = name
1690 && let virtual_path = old_name.path(RemapPathScopeComponents::MACRO)
1691 && let Ok(rest) = virtual_path.strip_prefix(virtual_dir)
1692 {
1693 let new_path = real_dir.join(rest);
1694
1695 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/rmeta/decoder.rs:1695",
"rustc_metadata::rmeta::decoder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/rmeta/decoder.rs"),
::tracing_core::__macro_support::Option::Some(1695u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::decoder"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("try_to_translate_virtual_to_real: `{0}` -> `{1}`",
virtual_path.display(), new_path.display()) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
1696 "try_to_translate_virtual_to_real: `{}` -> `{}`",
1697 virtual_path.display(),
1698 new_path.display(),
1699 );
1700
1701 *name = rustc_span::FileName::Real(
1707 tcx.sess
1708 .source_map()
1709 .path_mapping()
1710 .to_real_filename(&rustc_span::RealFileName::empty(), new_path),
1711 );
1712 }
1713 }
1714 };
1715
1716 let try_to_translate_real_to_virtual =
1717 |virtual_source_base_dir: Option<&str>,
1718 real_source_base_dir: &Option<PathBuf>,
1719 subdir: &str,
1720 name: &mut rustc_span::FileName| {
1721 if let Some(virtual_dir) =
1722 &tcx.sess.opts.unstable_opts.simulate_remapped_rust_src_base
1723 && let Some(real_dir) = real_source_base_dir
1724 && let rustc_span::FileName::Real(old_name) = name
1725 {
1726 let (_working_dir, embeddable_path) =
1727 old_name.embeddable_name(RemapPathScopeComponents::MACRO);
1728 let relative_path = embeddable_path.strip_prefix(real_dir).ok().or_else(|| {
1729 virtual_source_base_dir
1730 .and_then(|virtual_dir| embeddable_path.strip_prefix(virtual_dir).ok())
1731 });
1732 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/rmeta/decoder.rs:1732",
"rustc_metadata::rmeta::decoder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/rmeta/decoder.rs"),
::tracing_core::__macro_support::Option::Some(1732u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::decoder"),
::tracing_core::field::FieldSet::new(&["message",
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("relative_path")
}> =
::tracing::__macro_support::FieldName::new("relative_path");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("virtual_dir")
}> =
::tracing::__macro_support::FieldName::new("virtual_dir");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("subdir")
}> =
::tracing::__macro_support::FieldName::new("subdir");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("simulate_remapped_rust_src_base")
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&relative_path)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&virtual_dir)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&subdir)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
1733 ?relative_path,
1734 ?virtual_dir,
1735 ?subdir,
1736 "simulate_remapped_rust_src_base"
1737 );
1738 if let Some(rest) = relative_path.and_then(|p| p.strip_prefix(subdir).ok()) {
1739 *name =
1740 rustc_span::FileName::Real(rustc_span::RealFileName::from_virtual_path(
1741 &virtual_dir.join(subdir).join(rest),
1742 ))
1743 }
1744 }
1745 };
1746
1747 let mut import_info = self.source_map_import_info.lock();
1748 for _ in import_info.len()..=(source_file_index as usize) {
1749 import_info.push(None);
1750 }
1751 import_info[source_file_index as usize]
1752 .get_or_insert_with(|| {
1753 let source_file_to_import = self
1754 .root
1755 .source_map
1756 .get(self, source_file_index)
1757 .expect("missing source file")
1758 .decode((self, tcx));
1759
1760 let original_end_pos = source_file_to_import.end_position();
1763 let rustc_span::SourceFile {
1764 mut name,
1765 src_hash,
1766 checksum_hash,
1767 start_pos: original_start_pos,
1768 normalized_source_len,
1769 unnormalized_source_len,
1770 lines,
1771 multibyte_chars,
1772 normalized_pos,
1773 stable_id,
1774 ..
1775 } = source_file_to_import;
1776
1777 try_to_translate_real_to_virtual(
1785 ::core::option::Option::Some("/rustc/3d50c25bc66853bf0ad205529d0f305a1d841b5e")option_env!("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR"),
1786 &tcx.sess.opts.real_rust_source_base_dir,
1787 "library",
1788 &mut name,
1789 );
1790
1791 try_to_translate_real_to_virtual(
1796 ::core::option::Option::Some("/rustc-dev/3d50c25bc66853bf0ad205529d0f305a1d841b5e")option_env!("CFG_VIRTUAL_RUSTC_DEV_SOURCE_BASE_DIR"),
1797 &tcx.sess.opts.real_rustc_dev_source_base_dir,
1798 "compiler",
1799 &mut name,
1800 );
1801
1802 try_to_translate_virtual_to_real(
1808 ::core::option::Option::Some("/rustc/3d50c25bc66853bf0ad205529d0f305a1d841b5e")option_env!("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR"),
1809 &tcx.sess.opts.real_rust_source_base_dir,
1810 &mut name,
1811 );
1812
1813 try_to_translate_virtual_to_real(
1819 ::core::option::Option::Some("/rustc-dev/3d50c25bc66853bf0ad205529d0f305a1d841b5e")option_env!("CFG_VIRTUAL_RUSTC_DEV_SOURCE_BASE_DIR"),
1820 &tcx.sess.opts.real_rustc_dev_source_base_dir,
1821 &mut name,
1822 );
1823
1824 let local_version = tcx.sess.source_map().new_imported_source_file(
1825 name,
1826 src_hash,
1827 checksum_hash,
1828 stable_id,
1829 normalized_source_len.to_u32(),
1830 unnormalized_source_len,
1831 self.cnum,
1832 lines,
1833 multibyte_chars,
1834 normalized_pos,
1835 source_file_index,
1836 );
1837 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/rmeta/decoder.rs:1837",
"rustc_metadata::rmeta::decoder", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/rmeta/decoder.rs"),
::tracing_core::__macro_support::Option::Some(1837u32),
::tracing_core::__macro_support::Option::Some("rustc_metadata::rmeta::decoder"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("CrateMetaData::imported_source_files alloc source_file {0:?} original (start_pos {1:?} source_len {2:?}) translated (start_pos {3:?} source_len {4:?})",
local_version.name, original_start_pos,
normalized_source_len, local_version.start_pos,
local_version.normalized_source_len) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
1838 "CrateMetaData::imported_source_files alloc \
1839 source_file {:?} original (start_pos {:?} source_len {:?}) \
1840 translated (start_pos {:?} source_len {:?})",
1841 local_version.name,
1842 original_start_pos,
1843 normalized_source_len,
1844 local_version.start_pos,
1845 local_version.normalized_source_len
1846 );
1847
1848 ImportedSourceFile {
1849 original_start_pos,
1850 original_end_pos,
1851 translated_source_file: local_version,
1852 }
1853 })
1854 .clone()
1855 }
1856
1857 fn get_attr_flags(&self, index: DefIndex) -> AttrFlags {
1858 self.root.tables.attr_flags.get(self, index)
1859 }
1860
1861 fn get_intrinsic(&self, tcx: TyCtxt<'_>, index: DefIndex) -> Option<ty::IntrinsicDef> {
1862 self.root.tables.intrinsic.get(self, index).map(|d| d.decode((self, tcx)))
1863 }
1864
1865 fn get_doc_link_resolutions(&self, tcx: TyCtxt<'_>, index: DefIndex) -> DocLinkResMap {
1866 self.root
1867 .tables
1868 .doc_link_resolutions
1869 .get(self, index)
1870 .expect("no resolutions for a doc link")
1871 .decode((self, tcx))
1872 }
1873
1874 fn get_doc_link_traits_in_scope(
1875 &self,
1876 tcx: TyCtxt<'_>,
1877 index: DefIndex,
1878 ) -> impl Iterator<Item = DefId> {
1879 self.root
1880 .tables
1881 .doc_link_traits_in_scope
1882 .get(self, index)
1883 .expect("no traits in scope for a doc link")
1884 .decode((self, tcx))
1885 }
1886}
1887
1888impl CrateMetadata {
1889 pub(crate) fn new(
1890 tcx: TyCtxt<'_>,
1891 blob: MetadataBlob,
1892 root: CrateRoot,
1893 raw_proc_macros: Option<&'static [ProcMacroClient]>,
1894 cnum: CrateNum,
1895 cnum_map: CrateNumMap,
1896 dep_kind: CrateDepKind,
1897 source: CrateSource,
1898 private_dep: bool,
1899 host_hash: Option<Svh>,
1900 ) -> CrateMetadata {
1901 let trait_impls = root
1902 .impls
1903 .decode(&blob)
1904 .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls))
1905 .collect();
1906 let alloc_decoding_state =
1907 AllocDecodingState::new(root.interpret_alloc_index.decode(&blob).collect());
1908
1909 let def_path_hash_map = root.def_path_hash_map.decode(&blob);
1912
1913 let mut cdata = CrateMetadata {
1914 blob,
1915 root,
1916 trait_impls,
1917 incoherent_impls: Default::default(),
1918 raw_proc_macros,
1919 source_map_import_info: Lock::new(Vec::new()),
1920 def_path_hash_map,
1921 expn_hash_map: Default::default(),
1922 alloc_decoding_state,
1923 cnum,
1924 cnum_map,
1925 dep_kind,
1926 source: Arc::new(source),
1927 private_dep,
1928 host_hash,
1929 used: false,
1930 extern_crate: None,
1931 hygiene_context: Default::default(),
1932 def_key_cache: Default::default(),
1933 };
1934
1935 cdata.incoherent_impls = cdata
1936 .root
1937 .incoherent_impls
1938 .decode((&cdata, tcx))
1939 .map(|incoherent_impls| {
1940 (incoherent_impls.self_ty.decode((&cdata, tcx)), incoherent_impls.impls)
1941 })
1942 .collect();
1943
1944 cdata
1945 }
1946
1947 pub(crate) fn dependencies(&self) -> impl Iterator<Item = CrateNum> {
1948 self.cnum_map.iter().copied()
1949 }
1950
1951 pub(crate) fn target_modifiers(&self) -> TargetModifiers {
1952 self.root.decode_target_modifiers(&self.blob).collect()
1953 }
1954
1955 pub(crate) fn enabled_denied_partial_mitigations(&self) -> DeniedPartialMitigations {
1956 self.root.decode_denied_partial_mitigations(&self.blob).collect()
1957 }
1958
1959 pub(crate) fn update_extern_crate_diagnostics(
1961 &mut self,
1962 new_extern_crate: ExternCrate,
1963 ) -> bool {
1964 let update =
1965 self.extern_crate.as_ref().is_none_or(|old| old.rank() < new_extern_crate.rank());
1966 if update {
1967 self.extern_crate = Some(new_extern_crate);
1968 }
1969 update
1970 }
1971
1972 pub(crate) fn source(&self) -> &CrateSource {
1973 &*self.source
1974 }
1975
1976 pub(crate) fn dep_kind(&self) -> CrateDepKind {
1977 self.dep_kind
1978 }
1979
1980 pub(crate) fn set_dep_kind(&mut self, dep_kind: CrateDepKind) {
1981 self.dep_kind = dep_kind;
1982 }
1983
1984 pub(crate) fn update_and_private_dep(&mut self, private_dep: bool) {
1985 self.private_dep &= private_dep;
1986 }
1987
1988 pub(crate) fn used(&self) -> bool {
1989 self.used
1990 }
1991
1992 pub(crate) fn required_panic_strategy(&self) -> Option<PanicStrategy> {
1993 self.root.required_panic_strategy
1994 }
1995
1996 pub(crate) fn needs_panic_runtime(&self) -> bool {
1997 self.root.needs_panic_runtime
1998 }
1999
2000 pub(crate) fn is_private_dep(&self) -> bool {
2001 self.private_dep
2002 }
2003
2004 pub(crate) fn is_panic_runtime(&self) -> bool {
2005 self.root.panic_runtime
2006 }
2007
2008 pub(crate) fn is_profiler_runtime(&self) -> bool {
2009 self.root.profiler_runtime
2010 }
2011
2012 pub(crate) fn is_compiler_builtins(&self) -> bool {
2013 self.root.compiler_builtins
2014 }
2015
2016 pub(crate) fn needs_allocator(&self) -> bool {
2017 self.root.needs_allocator
2018 }
2019
2020 pub(crate) fn has_global_allocator(&self) -> bool {
2021 self.root.has_global_allocator
2022 }
2023
2024 pub(crate) fn has_alloc_error_handler(&self) -> bool {
2025 self.root.has_alloc_error_handler
2026 }
2027
2028 pub(crate) fn has_default_lib_allocator(&self) -> bool {
2029 self.root.has_default_lib_allocator
2030 }
2031
2032 pub(crate) fn is_proc_macro_crate(&self) -> bool {
2033 self.root.is_proc_macro_crate()
2034 }
2035
2036 pub(crate) fn proc_macros_for_crate(
2037 &self,
2038 tcx: TyCtxt<'_>,
2039 krate: CrateNum,
2040 ) -> impl Iterator<Item = DefId> {
2041 gen move {
2042 if let Some(data) = &self.root.proc_macro_data {
2043 for def_id in
2044 data.macros.decode((self, tcx)).map(move |(index, _)| DefId { index, krate })
2045 {
2046 yield def_id;
2047 }
2048 }
2049 }
2050 }
2051
2052 pub(crate) fn name(&self) -> Symbol {
2053 self.root.header.name
2054 }
2055
2056 pub(crate) fn hash(&self) -> Svh {
2057 self.root.header.hash
2058 }
2059
2060 pub(crate) fn has_async_drops(&self) -> bool {
2061 self.root.tables.adt_async_destructor.len > 0
2062 }
2063
2064 fn num_def_ids(&self) -> usize {
2065 self.root.tables.def_keys.size()
2066 }
2067
2068 fn local_def_id(&self, index: DefIndex) -> DefId {
2069 DefId { krate: self.cnum, index }
2070 }
2071
2072 fn reverse_translate_def_id(&self, did: DefId) -> Option<DefId> {
2075 for (local, &global) in self.cnum_map.iter_enumerated() {
2076 if global == did.krate {
2077 return Some(DefId { krate: local, index: did.index });
2078 }
2079 }
2080
2081 None
2082 }
2083}