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