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::attrs::CanonicalSymbols;
20use rustc_hir::def::Res;
21use rustc_hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE};
22use rustc_hir::definitions::{DefPath, DefPathData};
23use rustc_hir::diagnostic_items::DiagnosticItems;
24use rustc_index::Idx;
25use rustc_middle::middle::lib_features::LibFeatures;
26use rustc_middle::mir::interpret::{AllocDecodingSession, AllocDecodingState};
27use rustc_middle::ty::Visibility;
28use rustc_middle::ty::codec::TyDecoder;
29use rustc_middle::{bug, implement_ty_decoder};
30use rustc_proc_macro::bridge::client::Client as ProcMacroClient;
31use rustc_serialize::opaque::MemDecoder;
32use rustc_serialize::{Decodable, Decoder};
33use rustc_session::config::TargetModifier;
34use rustc_session::config::mitigation_coverage::DeniedPartialMitigation;
35use rustc_session::cstore::{CrateSource, ExternCrate};
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 safety: self.get_safety(did.index),
1149 value: self.get_default_field(tcx, did.index),
1150 })
1151 .collect(),
1152 parent_did,
1153 None,
1154 data.is_non_exhaustive,
1155 ),
1156 )
1157 }
1158
1159 fn get_adt_def<'tcx>(&self, tcx: TyCtxt<'tcx>, item_id: DefIndex) -> ty::AdtDef<'tcx> {
1160 let kind = self.def_kind(item_id);
1161 let did = self.local_def_id(item_id);
1162
1163 let adt_kind = match kind {
1164 DefKind::Enum => ty::AdtKind::Enum,
1165 DefKind::Struct => ty::AdtKind::Struct,
1166 DefKind::Union => ty::AdtKind::Union,
1167 _ => ::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),
1168 };
1169 let repr = self.root.tables.repr_options.get(self, item_id).unwrap().decode((self, tcx));
1170
1171 let mut variants: Vec<_> = if let ty::AdtKind::Enum = adt_kind {
1172 self.root
1173 .tables
1174 .module_children_non_reexports
1175 .get(self, item_id)
1176 .expect("variants are not encoded for an enum")
1177 .decode((self, tcx))
1178 .filter_map(|index| {
1179 let kind = self.def_kind(index);
1180 match kind {
1181 DefKind::Ctor(..) => None,
1182 _ => Some(self.get_variant(tcx, kind, index, did)),
1183 }
1184 })
1185 .collect()
1186 } else {
1187 std::iter::once(self.get_variant(tcx, kind, item_id, did)).collect()
1188 };
1189
1190 variants.sort_by_key(|(idx, _)| *idx);
1191
1192 tcx.mk_adt_def(
1193 did,
1194 adt_kind,
1195 variants.into_iter().map(|(_, variant)| variant).collect(),
1196 repr,
1197 )
1198 }
1199
1200 fn get_visibility(&self, tcx: TyCtxt<'_>, id: DefIndex) -> Visibility<ModId> {
1201 self.root
1202 .tables
1203 .visibility
1204 .get(self, id)
1205 .unwrap_or_else(|| self.missing("visibility", id))
1206 .decode((self, tcx))
1207 .map_id(|index| ModId::new_unchecked(self.local_def_id(index)))
1208 }
1209
1210 fn get_safety(&self, id: DefIndex) -> Safety {
1211 self.root.tables.safety.get(self, id)
1212 }
1213
1214 fn get_default_field(&self, tcx: TyCtxt<'_>, id: DefIndex) -> Option<DefId> {
1215 self.root.tables.default_fields.get(self, id).map(|d| d.decode((self, tcx)))
1216 }
1217
1218 fn get_expn_that_defined(&self, tcx: TyCtxt<'_>, id: DefIndex) -> ExpnId {
1219 self.root
1220 .tables
1221 .expn_that_defined
1222 .get(self, id)
1223 .unwrap_or_else(|| self.missing("expn_that_defined", id))
1224 .decode((self, tcx))
1225 }
1226
1227 fn get_debugger_visualizers(&self, tcx: TyCtxt<'_>) -> Vec<DebuggerVisualizerFile> {
1228 self.root.debugger_visualizers.decode((self, tcx)).collect::<Vec<_>>()
1229 }
1230
1231 fn get_lib_features(&self, tcx: TyCtxt<'_>) -> LibFeatures {
1233 LibFeatures {
1234 stability: self
1235 .root
1236 .lib_features
1237 .decode((self, tcx))
1238 .map(|(sym, stab)| (sym, (stab, DUMMY_SP)))
1239 .collect(),
1240 }
1241 }
1242
1243 fn get_stability_implications<'tcx>(&self, tcx: TyCtxt<'tcx>) -> &'tcx [(Symbol, Symbol)] {
1247 tcx.arena.alloc_from_iter(self.root.stability_implications.decode((self, tcx)))
1248 }
1249
1250 fn get_lang_items<'tcx>(&self, tcx: TyCtxt<'tcx>) -> &'tcx [(DefId, LangItem)] {
1252 tcx.arena.alloc_from_iter(
1253 self.root
1254 .lang_items
1255 .decode((self, tcx))
1256 .map(move |(def_index, index)| (self.local_def_id(def_index), index)),
1257 )
1258 }
1259
1260 fn get_stripped_cfg_items<'tcx>(
1261 &self,
1262 tcx: TyCtxt<'tcx>,
1263 cnum: CrateNum,
1264 ) -> &'tcx [StrippedCfgItem] {
1265 let item_names = self
1266 .root
1267 .stripped_cfg_items
1268 .decode((self, tcx))
1269 .map(|item| item.map_scope_id(|index| DefId { krate: cnum, index }));
1270 tcx.arena.alloc_from_iter(item_names)
1271 }
1272
1273 fn get_diagnostic_items(&self, tcx: TyCtxt<'_>) -> DiagnosticItems {
1275 let mut id_to_name = DefIdMap::default();
1276 let name_to_id = self
1277 .root
1278 .diagnostic_items
1279 .decode((self, tcx))
1280 .map(|(name, def_index)| {
1281 let id = self.local_def_id(def_index);
1282 id_to_name.insert(id, name);
1283 (name, id)
1284 })
1285 .collect();
1286 DiagnosticItems { id_to_name, name_to_id }
1287 }
1288
1289 fn get_canonical_symbols(&self, tcx: TyCtxt<'_>) -> CanonicalSymbols {
1291 let mut canonical_symbols = CanonicalSymbols::new();
1292
1293 for (name, def_index) in self.root.canonical_symbols.decode((self, tcx)) {
1294 let id = self.local_def_id(def_index);
1295 let _ = canonical_symbols.set(name, id);
1296 }
1297
1298 canonical_symbols
1299 }
1300
1301 fn get_mod_child(&self, tcx: TyCtxt<'_>, id: DefIndex) -> ModChild {
1302 let ident = self.item_ident(tcx, id);
1303 let res = Res::Def(self.def_kind(id), self.local_def_id(id));
1304 let vis = self.get_visibility(tcx, id);
1305
1306 ModChild { ident, res, vis, reexport_chain: Default::default() }
1307 }
1308
1309 fn get_module_children(&self, tcx: TyCtxt<'_>, id: DefIndex) -> impl Iterator<Item = ModChild> {
1318 gen move {
1319 if let Some(data) = &self.root.proc_macro_data {
1320 if id == CRATE_DEF_INDEX {
1323 for (child_index, _) in data.macros.decode((self, tcx)) {
1324 yield self.get_mod_child(tcx, child_index);
1325 }
1326 }
1327 } else {
1328 let non_reexports = self.root.tables.module_children_non_reexports.get(self, id);
1330 let non_reexports =
1331 non_reexports.expect("provided `DefIndex` must refer to a module-like item");
1332 for child_index in non_reexports.decode((self, tcx)) {
1333 yield self.get_mod_child(tcx, child_index);
1334 }
1335
1336 let reexports = self.root.tables.module_children_reexports.get(self, id);
1337 if !reexports.is_default() {
1338 for reexport in reexports.decode((self, tcx)) {
1339 yield reexport;
1340 }
1341 }
1342 }
1343 }
1344 }
1345
1346 fn get_ambig_module_children(
1347 &self,
1348 tcx: TyCtxt<'_>,
1349 id: DefIndex,
1350 ) -> impl Iterator<Item = AmbigModChild> {
1351 gen move {
1352 let children = self.root.tables.ambig_module_children.get(self, id);
1353 if !children.is_default() {
1354 for child in children.decode((self, tcx)) {
1355 yield child;
1356 }
1357 }
1358 }
1359 }
1360
1361 fn is_item_mir_available(&self, id: DefIndex) -> bool {
1362 self.root.tables.optimized_mir.get(self, id).is_some()
1363 }
1364
1365 fn get_fn_has_self_parameter(&self, tcx: TyCtxt<'_>, id: DefIndex) -> bool {
1366 self.root
1367 .tables
1368 .fn_arg_idents
1369 .get(self, id)
1370 .expect("argument names not encoded for a function")
1371 .decode((self, tcx))
1372 .nth(0)
1373 .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, .. })))
1374 }
1375
1376 fn get_associated_item_or_field_def_ids(
1377 &self,
1378 tcx: TyCtxt<'_>,
1379 id: DefIndex,
1380 ) -> impl Iterator<Item = DefId> {
1381 self.root
1382 .tables
1383 .associated_item_or_field_def_ids
1384 .get(self, id)
1385 .unwrap_or_else(|| self.missing("associated_item_or_field_def_ids", id))
1386 .decode((self, tcx))
1387 .map(move |child_index| self.local_def_id(child_index))
1388 }
1389
1390 fn get_associated_item(&self, tcx: TyCtxt<'_>, id: DefIndex) -> ty::AssocItem {
1391 let kind = match self.def_kind(id) {
1392 DefKind::AssocConst { is_type_const } => {
1393 ty::AssocKind::Const { name: self.item_name(id), is_type_const }
1394 }
1395 DefKind::AssocFn => ty::AssocKind::Fn {
1396 name: self.item_name(id),
1397 has_self: self.get_fn_has_self_parameter(tcx, id),
1398 },
1399 DefKind::AssocTy => {
1400 let data = if let Some(rpitit_info) = self.root.tables.opt_rpitit_info.get(self, id)
1401 {
1402 ty::AssocTypeData::Rpitit(rpitit_info.decode((self, tcx)))
1403 } else {
1404 ty::AssocTypeData::Normal(self.item_name(id))
1405 };
1406 ty::AssocKind::Type { data }
1407 }
1408 _ => ::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)),
1409 };
1410 let container = self.root.tables.assoc_container.get(self, id).unwrap().decode((self, tcx));
1411
1412 ty::AssocItem { kind, def_id: self.local_def_id(id), container }
1413 }
1414
1415 fn get_ctor(&self, tcx: TyCtxt<'_>, node_id: DefIndex) -> Option<(CtorKind, DefId)> {
1416 match self.def_kind(node_id) {
1417 DefKind::Struct | DefKind::Variant => {
1418 let vdata =
1419 self.root.tables.variant_data.get(self, node_id).unwrap().decode((self, tcx));
1420 vdata.ctor.map(|(kind, index)| (kind, self.local_def_id(index)))
1421 }
1422 _ => None,
1423 }
1424 }
1425
1426 fn get_item_attrs(
1427 &self,
1428 tcx: TyCtxt<'_>,
1429 id: DefIndex,
1430 ) -> impl Iterator<Item = hir::Attribute> {
1431 self.root
1432 .tables
1433 .attributes
1434 .get(self, id)
1435 .unwrap_or_else(|| {
1436 let def_key = self.def_key(id);
1437 match def_key.disambiguated_data.data {
1438 DefPathData::Ctor => {
1439 {
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);
1443 let parent_id = def_key.parent.expect("no parent for a constructor");
1444 self.root
1445 .tables
1446 .attributes
1447 .get(self, parent_id)
1448 .expect("no encoded attributes for a structure or variant")
1449 }
1450 DefPathData::SyntheticCoroutineBody => {
1451 LazyArray::default()
1453 }
1454 _ => {
::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)
1455 }
1456 })
1457 .decode((self, tcx))
1458 }
1459
1460 fn get_inherent_implementations_for_type<'tcx>(
1461 &self,
1462 tcx: TyCtxt<'tcx>,
1463 id: DefIndex,
1464 ) -> &'tcx [DefId] {
1465 tcx.arena.alloc_from_iter(
1466 self.root
1467 .tables
1468 .inherent_impls
1469 .get(self, id)
1470 .decode((self, tcx))
1471 .map(|index| self.local_def_id(index)),
1472 )
1473 }
1474
1475 fn get_traits(&self, tcx: TyCtxt<'_>) -> impl Iterator<Item = DefId> {
1477 self.root.traits.decode((self, tcx)).map(move |index| self.local_def_id(index))
1478 }
1479
1480 fn get_trait_impls(&self, tcx: TyCtxt<'_>) -> impl Iterator<Item = DefId> {
1482 self.trait_impls.values().flat_map(move |impls| {
1483 impls.decode((self, tcx)).map(move |(impl_index, _)| self.local_def_id(impl_index))
1484 })
1485 }
1486
1487 fn get_incoherent_impls<'tcx>(&self, tcx: TyCtxt<'tcx>, simp: SimplifiedType) -> &'tcx [DefId] {
1488 if let Some(impls) = self.incoherent_impls.get(&simp) {
1489 tcx.arena.alloc_from_iter(impls.decode((self, tcx)).map(|idx| self.local_def_id(idx)))
1490 } else {
1491 &[]
1492 }
1493 }
1494
1495 fn get_implementations_of_trait<'tcx>(
1496 &self,
1497 tcx: TyCtxt<'tcx>,
1498 trait_def_id: DefId,
1499 ) -> &'tcx [(DefId, Option<SimplifiedType>)] {
1500 if self.trait_impls.is_empty() {
1501 return &[];
1502 }
1503
1504 let key = match self.reverse_translate_def_id(trait_def_id) {
1507 Some(def_id) => (def_id.krate.as_u32(), def_id.index),
1508 None => return &[],
1509 };
1510
1511 if let Some(impls) = self.trait_impls.get(&key) {
1512 tcx.arena.alloc_from_iter(
1513 impls
1514 .decode((self, tcx))
1515 .map(|(idx, simplified_self_ty)| (self.local_def_id(idx), simplified_self_ty)),
1516 )
1517 } else {
1518 &[]
1519 }
1520 }
1521
1522 fn get_native_libraries(&self, tcx: TyCtxt<'_>) -> impl Iterator<Item = NativeLib> {
1523 self.root.native_libraries.decode((self, tcx))
1524 }
1525
1526 fn get_proc_macro_quoted_span(&self, tcx: TyCtxt<'_>, index: usize) -> Span {
1527 self.root
1528 .tables
1529 .proc_macro_quoted_spans
1530 .get(self, index)
1531 .unwrap_or_else(|| {
::core::panicking::panic_fmt(format_args!("Missing proc macro quoted span: {0:?}",
index));
}panic!("Missing proc macro quoted span: {index:?}"))
1532 .decode((self, tcx))
1533 }
1534
1535 fn get_foreign_modules(&self, tcx: TyCtxt<'_>) -> impl Iterator<Item = ForeignModule> {
1536 self.root.foreign_modules.decode((self, tcx))
1537 }
1538
1539 fn get_dylib_dependency_formats<'tcx>(
1540 &self,
1541 tcx: TyCtxt<'tcx>,
1542 ) -> &'tcx [(CrateNum, LinkagePreference)] {
1543 tcx.arena.alloc_from_iter(
1544 self.root.dylib_dependency_formats.decode((self, tcx)).enumerate().flat_map(
1545 |(i, link)| {
1546 let cnum = CrateNum::new(i + 1); link.map(|link| (self.cnum_map[cnum], link))
1548 },
1549 ),
1550 )
1551 }
1552
1553 fn get_externally_implementable_items(
1554 &self,
1555 tcx: TyCtxt<'_>,
1556 ) -> impl Iterator<Item = EiiMapEncodedKeyValue> {
1557 self.root.externally_implementable_items.decode((self, tcx))
1558 }
1559
1560 fn get_missing_lang_items<'tcx>(&self, tcx: TyCtxt<'tcx>) -> &'tcx [LangItem] {
1561 tcx.arena.alloc_from_iter(self.root.lang_items_missing.decode((self, tcx)))
1562 }
1563
1564 fn get_exportable_items(&self, tcx: TyCtxt<'_>) -> impl Iterator<Item = DefId> {
1565 self.root.exportable_items.decode((self, tcx)).map(move |index| self.local_def_id(index))
1566 }
1567
1568 fn get_stable_order_of_exportable_impls(
1569 &self,
1570 tcx: TyCtxt<'_>,
1571 ) -> impl Iterator<Item = (DefId, usize)> {
1572 self.root
1573 .stable_order_of_exportable_impls
1574 .decode((self, tcx))
1575 .map(move |v| (self.local_def_id(v.0), v.1))
1576 }
1577
1578 fn exported_non_generic_symbols<'tcx>(
1579 &self,
1580 tcx: TyCtxt<'tcx>,
1581 ) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportInfo)] {
1582 tcx.arena.alloc_from_iter(self.root.exported_non_generic_symbols.decode((self, tcx)))
1583 }
1584
1585 fn exported_generic_symbols<'tcx>(
1586 &self,
1587 tcx: TyCtxt<'tcx>,
1588 ) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportInfo)] {
1589 tcx.arena.alloc_from_iter(self.root.exported_generic_symbols.decode((self, tcx)))
1590 }
1591
1592 fn get_macro(&self, tcx: TyCtxt<'_>, id: DefIndex) -> ast::MacroDef {
1593 match self.def_kind(id) {
1594 DefKind::Macro(_) => {
1595 let macro_rules = self.root.tables.is_macro_rules.get(self, id);
1596 let body =
1597 self.root.tables.macro_definition.get(self, id).unwrap().decode((self, tcx));
1598 ast::MacroDef { macro_rules, body: Box::new(body), eii_declaration: None }
1599 }
1600 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
1601 }
1602 }
1603
1604 #[inline]
1605 fn def_key(&self, index: DefIndex) -> DefKey {
1606 *self.def_key_cache.lock().entry(index).or_insert_with(|| {
1607 self.root.tables.def_keys.get(&self.blob, index).unwrap().decode(&self.blob)
1608 })
1609 }
1610
1611 fn def_path(&self, id: DefIndex) -> DefPath {
1613 {
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:1613",
"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(1613u32),
::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);
1614 DefPath::make(self.cnum, id, |parent| self.def_key(parent))
1615 }
1616
1617 #[inline]
1618 fn def_path_hash(&self, index: DefIndex) -> DefPathHash {
1619 let fingerprint = Fingerprint::new(
1623 self.root.stable_crate_id.as_u64(),
1624 self.root.tables.def_path_hashes.get(&self.blob, index),
1625 );
1626 DefPathHash::new(self.root.stable_crate_id, fingerprint.split().1)
1627 }
1628
1629 #[inline]
1630 fn def_path_hash_to_def_index(&self, hash: DefPathHash) -> Option<DefIndex> {
1631 self.def_path_hash_map.def_path_hash_to_def_index(&hash)
1632 }
1633
1634 fn expn_hash_to_expn_id(&self, tcx: TyCtxt<'_>, index_guess: u32, hash: ExpnHash) -> ExpnId {
1635 let index_guess = ExpnIndex::from_u32(index_guess);
1636 let old_hash =
1637 self.root.expn_hashes.get(self, index_guess).map(|lazy| lazy.decode((self, tcx)));
1638
1639 let index = if old_hash == Some(hash) {
1640 index_guess
1644 } else {
1645 let map = self.expn_hash_map.get_or_init(|| {
1649 let end_id = self.root.expn_hashes.size() as u32;
1650 let mut map =
1651 UnhashMap::with_capacity_and_hasher(end_id as usize, Default::default());
1652 for i in 0..end_id {
1653 let i = ExpnIndex::from_u32(i);
1654 if let Some(hash) = self.root.expn_hashes.get(self, i) {
1655 map.insert(hash.decode((self, tcx)), i);
1656 }
1657 }
1658 map
1659 });
1660 map[&hash]
1661 };
1662
1663 let data = self.root.expn_data.get(self, index).unwrap().decode((self, tcx));
1664 rustc_span::hygiene::register_expn_id(self.cnum, index, data, hash)
1665 }
1666
1667 fn imported_source_file(&self, tcx: TyCtxt<'_>, source_file_index: u32) -> ImportedSourceFile {
1693 fn filter<'a>(
1694 tcx: TyCtxt<'_>,
1695 real_source_base_dir: &Option<PathBuf>,
1696 path: Option<&'a Path>,
1697 ) -> Option<&'a Path> {
1698 path.filter(|_| {
1699 real_source_base_dir.is_some()
1701 && tcx.sess.opts.unstable_opts.translate_remapped_path_to_local_path
1703 })
1704 .filter(|virtual_dir| {
1705 !tcx.sess.opts.remap_path_prefix.iter().any(|(_from, to)| to == virtual_dir)
1709 })
1710 }
1711
1712 let try_to_translate_virtual_to_real =
1713 |virtual_source_base_dir: Option<&str>,
1714 real_source_base_dir: &Option<PathBuf>,
1715 name: &mut rustc_span::FileName| {
1716 let virtual_source_base_dir = [
1717 filter(tcx, real_source_base_dir, virtual_source_base_dir.map(Path::new)),
1718 filter(
1719 tcx,
1720 real_source_base_dir,
1721 tcx.sess.opts.unstable_opts.simulate_remapped_rust_src_base.as_deref(),
1722 ),
1723 ];
1724
1725 {
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:1725",
"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(1725u32),
::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!(
1726 "try_to_translate_virtual_to_real(name={:?}): \
1727 virtual_source_base_dir={:?}, real_source_base_dir={:?}",
1728 name, virtual_source_base_dir, real_source_base_dir,
1729 );
1730
1731 for virtual_dir in virtual_source_base_dir.iter().flatten() {
1732 if let Some(real_dir) = &real_source_base_dir
1733 && let rustc_span::FileName::Real(old_name) = name
1734 && let virtual_path = old_name.path(RemapPathScopeComponents::MACRO)
1735 && let Ok(rest) = virtual_path.strip_prefix(virtual_dir)
1736 {
1737 let new_path = real_dir.join(rest);
1738
1739 {
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:1739",
"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(1739u32),
::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!(
1740 "try_to_translate_virtual_to_real: `{}` -> `{}`",
1741 virtual_path.display(),
1742 new_path.display(),
1743 );
1744
1745 *name = rustc_span::FileName::Real(
1751 tcx.sess
1752 .source_map()
1753 .path_mapping()
1754 .to_real_filename(&rustc_span::RealFileName::empty(), new_path),
1755 );
1756 }
1757 }
1758 };
1759
1760 let try_to_translate_real_to_virtual =
1761 |virtual_source_base_dir: Option<&str>,
1762 real_source_base_dir: &Option<PathBuf>,
1763 subdir: &str,
1764 name: &mut rustc_span::FileName| {
1765 if let Some(virtual_dir) =
1766 &tcx.sess.opts.unstable_opts.simulate_remapped_rust_src_base
1767 && let Some(real_dir) = real_source_base_dir
1768 && let rustc_span::FileName::Real(old_name) = name
1769 {
1770 let (_working_dir, embeddable_path) =
1771 old_name.embeddable_name(RemapPathScopeComponents::MACRO);
1772 let relative_path = embeddable_path.strip_prefix(real_dir).ok().or_else(|| {
1773 virtual_source_base_dir
1774 .and_then(|virtual_dir| embeddable_path.strip_prefix(virtual_dir).ok())
1775 });
1776 {
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:1776",
"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(1776u32),
::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!(
1777 ?relative_path,
1778 ?virtual_dir,
1779 ?subdir,
1780 "simulate_remapped_rust_src_base"
1781 );
1782 if let Some(rest) = relative_path.and_then(|p| p.strip_prefix(subdir).ok()) {
1783 *name =
1784 rustc_span::FileName::Real(rustc_span::RealFileName::from_virtual_path(
1785 &virtual_dir.join(subdir).join(rest),
1786 ))
1787 }
1788 }
1789 };
1790
1791 let mut import_info = self.source_map_import_info.lock();
1792 for _ in import_info.len()..=(source_file_index as usize) {
1793 import_info.push(None);
1794 }
1795 import_info[source_file_index as usize]
1796 .get_or_insert_with(|| {
1797 let source_file_to_import = self
1798 .root
1799 .source_map
1800 .get(self, source_file_index)
1801 .expect("missing source file")
1802 .decode((self, tcx));
1803
1804 let original_end_pos = source_file_to_import.end_position();
1807 let rustc_span::SourceFile {
1808 mut name,
1809 src_hash,
1810 checksum_hash,
1811 start_pos: original_start_pos,
1812 normalized_source_len,
1813 unnormalized_source_len,
1814 lines,
1815 multibyte_chars,
1816 normalized_pos,
1817 stable_id,
1818 ..
1819 } = source_file_to_import;
1820
1821 try_to_translate_real_to_virtual(
1829 ::core::option::Option::Some("/rustc/1a833e16546c2eb012758ddd499964fd8afee29e")option_env!("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR"),
1830 &tcx.sess.opts.real_rust_source_base_dir,
1831 "library",
1832 &mut name,
1833 );
1834
1835 try_to_translate_real_to_virtual(
1840 ::core::option::Option::Some("/rustc-dev/1a833e16546c2eb012758ddd499964fd8afee29e")option_env!("CFG_VIRTUAL_RUSTC_DEV_SOURCE_BASE_DIR"),
1841 &tcx.sess.opts.real_rustc_dev_source_base_dir,
1842 "compiler",
1843 &mut name,
1844 );
1845
1846 try_to_translate_virtual_to_real(
1852 ::core::option::Option::Some("/rustc/1a833e16546c2eb012758ddd499964fd8afee29e")option_env!("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR"),
1853 &tcx.sess.opts.real_rust_source_base_dir,
1854 &mut name,
1855 );
1856
1857 try_to_translate_virtual_to_real(
1863 ::core::option::Option::Some("/rustc-dev/1a833e16546c2eb012758ddd499964fd8afee29e")option_env!("CFG_VIRTUAL_RUSTC_DEV_SOURCE_BASE_DIR"),
1864 &tcx.sess.opts.real_rustc_dev_source_base_dir,
1865 &mut name,
1866 );
1867
1868 let local_version = tcx.sess.source_map().new_imported_source_file(
1869 name,
1870 src_hash,
1871 checksum_hash,
1872 stable_id,
1873 normalized_source_len.to_u32(),
1874 unnormalized_source_len,
1875 self.cnum,
1876 lines,
1877 multibyte_chars,
1878 normalized_pos,
1879 source_file_index,
1880 );
1881 {
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:1881",
"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(1881u32),
::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!(
1882 "CrateMetaData::imported_source_files alloc \
1883 source_file {:?} original (start_pos {:?} source_len {:?}) \
1884 translated (start_pos {:?} source_len {:?})",
1885 local_version.name,
1886 original_start_pos,
1887 normalized_source_len,
1888 local_version.start_pos,
1889 local_version.normalized_source_len
1890 );
1891
1892 ImportedSourceFile {
1893 original_start_pos,
1894 original_end_pos,
1895 translated_source_file: local_version,
1896 }
1897 })
1898 .clone()
1899 }
1900
1901 fn get_attr_flags(&self, index: DefIndex) -> AttrFlags {
1902 self.root.tables.attr_flags.get(self, index)
1903 }
1904
1905 fn get_intrinsic(&self, tcx: TyCtxt<'_>, index: DefIndex) -> Option<ty::IntrinsicDef> {
1906 self.root.tables.intrinsic.get(self, index).map(|d| d.decode((self, tcx)))
1907 }
1908
1909 fn get_doc_link_resolutions(&self, tcx: TyCtxt<'_>, index: DefIndex) -> DocLinkResMap {
1910 self.root
1911 .tables
1912 .doc_link_resolutions
1913 .get(self, index)
1914 .expect("no resolutions for a doc link")
1915 .decode((self, tcx))
1916 }
1917
1918 fn get_doc_link_traits_in_scope(
1919 &self,
1920 tcx: TyCtxt<'_>,
1921 index: DefIndex,
1922 ) -> impl Iterator<Item = DefId> {
1923 self.root
1924 .tables
1925 .doc_link_traits_in_scope
1926 .get(self, index)
1927 .expect("no traits in scope for a doc link")
1928 .decode((self, tcx))
1929 }
1930}
1931
1932impl CrateMetadata {
1933 pub(crate) fn new(
1934 tcx: TyCtxt<'_>,
1935 blob: MetadataBlob,
1936 root: CrateRoot,
1937 raw_proc_macros: Option<&'static [ProcMacroClient]>,
1938 cnum: CrateNum,
1939 cnum_map: CrateNumMap,
1940 dep_kind: CrateDepKind,
1941 source: CrateSource,
1942 private_dep: bool,
1943 host_hash: Option<Svh>,
1944 ) -> CrateMetadata {
1945 let trait_impls = root
1946 .impls
1947 .decode(&blob)
1948 .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls))
1949 .collect();
1950 let alloc_decoding_state =
1951 AllocDecodingState::new(root.interpret_alloc_index.decode(&blob).collect());
1952
1953 let def_path_hash_map = root.def_path_hash_map.decode(&blob);
1956
1957 let mut cdata = CrateMetadata {
1958 blob,
1959 root,
1960 trait_impls,
1961 incoherent_impls: Default::default(),
1962 raw_proc_macros,
1963 source_map_import_info: Lock::new(Vec::new()),
1964 def_path_hash_map,
1965 expn_hash_map: Default::default(),
1966 alloc_decoding_state,
1967 cnum,
1968 cnum_map,
1969 dep_kind,
1970 source: Arc::new(source),
1971 private_dep,
1972 host_hash,
1973 used: false,
1974 extern_crate: None,
1975 hygiene_context: Default::default(),
1976 def_key_cache: Default::default(),
1977 };
1978
1979 cdata.incoherent_impls = cdata
1980 .root
1981 .incoherent_impls
1982 .decode((&cdata, tcx))
1983 .map(|incoherent_impls| {
1984 (incoherent_impls.self_ty.decode((&cdata, tcx)), incoherent_impls.impls)
1985 })
1986 .collect();
1987
1988 cdata
1989 }
1990
1991 pub(crate) fn dependencies(&self) -> impl Iterator<Item = CrateNum> {
1992 self.cnum_map.iter().copied()
1993 }
1994
1995 pub(crate) fn target_modifiers(&self) -> TargetModifiers {
1996 self.root.decode_target_modifiers(&self.blob).collect()
1997 }
1998
1999 pub(crate) fn enabled_denied_partial_mitigations(&self) -> DeniedPartialMitigations {
2000 self.root.decode_denied_partial_mitigations(&self.blob).collect()
2001 }
2002
2003 pub(crate) fn update_extern_crate_diagnostics(
2005 &mut self,
2006 new_extern_crate: ExternCrate,
2007 ) -> bool {
2008 let update =
2009 self.extern_crate.as_ref().is_none_or(|old| old.rank() < new_extern_crate.rank());
2010 if update {
2011 self.extern_crate = Some(new_extern_crate);
2012 }
2013 update
2014 }
2015
2016 pub(crate) fn source(&self) -> &CrateSource {
2017 &*self.source
2018 }
2019
2020 pub(crate) fn dep_kind(&self) -> CrateDepKind {
2021 self.dep_kind
2022 }
2023
2024 pub(crate) fn set_dep_kind(&mut self, dep_kind: CrateDepKind) {
2025 self.dep_kind = dep_kind;
2026 }
2027
2028 pub(crate) fn update_and_private_dep(&mut self, private_dep: bool) {
2029 self.private_dep &= private_dep;
2030 }
2031
2032 pub(crate) fn used(&self) -> bool {
2033 self.used
2034 }
2035
2036 pub(crate) fn required_panic_strategy(&self) -> Option<PanicStrategy> {
2037 self.root.required_panic_strategy
2038 }
2039
2040 pub(crate) fn needs_panic_runtime(&self) -> bool {
2041 self.root.needs_panic_runtime
2042 }
2043
2044 pub(crate) fn is_private_dep(&self) -> bool {
2045 self.private_dep
2046 }
2047
2048 pub(crate) fn is_panic_runtime(&self) -> bool {
2049 self.root.panic_runtime
2050 }
2051
2052 pub(crate) fn is_profiler_runtime(&self) -> bool {
2053 self.root.profiler_runtime
2054 }
2055
2056 pub(crate) fn is_compiler_builtins(&self) -> bool {
2057 self.root.compiler_builtins
2058 }
2059
2060 pub(crate) fn needs_allocator(&self) -> bool {
2061 self.root.needs_allocator
2062 }
2063
2064 pub(crate) fn has_global_allocator(&self) -> bool {
2065 self.root.has_global_allocator
2066 }
2067
2068 pub(crate) fn has_alloc_error_handler(&self) -> bool {
2069 self.root.has_alloc_error_handler
2070 }
2071
2072 pub(crate) fn has_default_lib_allocator(&self) -> bool {
2073 self.root.has_default_lib_allocator
2074 }
2075
2076 pub(crate) fn is_proc_macro_crate(&self) -> bool {
2077 self.root.is_proc_macro_crate()
2078 }
2079
2080 pub(crate) fn proc_macros_for_crate(
2081 &self,
2082 tcx: TyCtxt<'_>,
2083 krate: CrateNum,
2084 ) -> impl Iterator<Item = DefId> {
2085 gen move {
2086 if let Some(data) = &self.root.proc_macro_data {
2087 for def_id in
2088 data.macros.decode((self, tcx)).map(move |(index, _)| DefId { index, krate })
2089 {
2090 yield def_id;
2091 }
2092 }
2093 }
2094 }
2095
2096 pub(crate) fn name(&self) -> Symbol {
2097 self.root.header.name
2098 }
2099
2100 pub(crate) fn hash(&self) -> Svh {
2101 self.root.header.hash
2102 }
2103
2104 pub(crate) fn has_async_drops(&self) -> bool {
2105 self.root.tables.adt_async_destructor.len > 0
2106 }
2107
2108 fn num_def_ids(&self) -> usize {
2109 self.root.tables.def_keys.size()
2110 }
2111
2112 fn local_def_id(&self, index: DefIndex) -> DefId {
2113 DefId { krate: self.cnum, index }
2114 }
2115
2116 fn reverse_translate_def_id(&self, did: DefId) -> Option<DefId> {
2119 for (local, &global) in self.cnum_map.iter_enumerated() {
2120 if global == did.krate {
2121 return Some(DefId { krate: local, index: did.index });
2122 }
2123 }
2124
2125 None
2126 }
2127}